product of arrays other than themselves
Topic description: Given an integer array nums of length n, where n > 1, return the output array output, where output[i] is equal to the product of the elements in nums except nums[i].
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/product-of-array-except-self/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array Traversal
The general idea is to traverse two groups of times to calculate the prefix product and the suffix product respectively, and multiply them during the period. The specific processing process is as follows:
- First, declare an array of the same size as the original array to temporarily store the accumulated product;
- Then, traverse the array from front to back to record the prefix accumulation of each position;
- Then, traverse the array from back to front and calculate the suffix cumulative product of each position, and multiply the prefix cumulative product obtained by the previous traversal to obtain the non-self cumulative product of the corresponding position.
Finally, this temporary array is returned as the result.
import java.util.Arrays;
public class LeetCode_238 {
public static int[] productExceptSelf(int[] nums) {
int len = nums.length;
int[] temp = new int[len];
// 由于是算乘积,先都初始化为1
Arrays.fill(temp, 1);
// 计算前缀和乘积 temp[i]表示第i个数前面所有数的乘积
for (int i = 1; i < len; i++) {
temp[i] = temp[i - 1] * nums[i - 1];
}
// 递推求后缀和乘积,同时将结果放到前缀和数组中
// 从后往前,因为要递推后缀和乘积,末尾的初始为1
for (int i = len - 1, subfixS = 1; i >= 0; i--) {
// 当前数的乘积结果等于 前缀和乘后缀和
temp[i] = temp[i] * subfixS;
// 更新后缀和
subfixS *= nums[i];
}
return temp;
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 3, 4};
// 测试用例,期望输出: [24,12,8,6]
for (int i : productExceptSelf(nums)) {
System.out.print(i + " ");
}
}
}
[Daily Message] Maybe I am not the best, but I am the hardest.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。