leetcode

Product of Array Except Self

Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

1
2
Input:  [1,2,3,4]
Output: [24,12,8,6]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
Arrays.fill(ans, 1);
for (int i = 1; i < n; i++) {
ans[i] = nums[i - 1] * ans[i - 1];
}
int tmp = 1;
for (int i = n - 2; i >= 0; i--) {
tmp *= nums[i + 1];
ans[i] *= tmp;
}
return ans;
}
-------------本文结束感谢您的阅读-------------
undefined