題目
Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
Input:
- 數(shù)組 :: int[]
Output:
- 每一位存除這個數(shù)以外其他數(shù)的乘積 :: int[]
Intuition:
用constant的space,還有比這更露骨的提示嘛?除了two pointers 還能想到啥。左邊的指針掃一遍,把每個數(shù)左邊的乘積搞定,右邊指針右邊掃一遍,把右邊的乘積搞定就OK了。
但素,我居然還是卡住了,數(shù)學(xué)不好的同學(xué)們,還是要寫幾個case確定你的關(guān)系式是正確的,兩邊的margin要處理正確。
public int[] productExceptSelf(int[] nums) {
int[] res = new int[nums.length];
int len = nums.length;
int left = nums[0];
res[0] = 1;
//find product on the left side
for (int i = 1; i < len; i++){
res[i] = left;
left *= nums[i];
}
//find product on the right side and multipy it with left side product
int right = nums[nums.length - 1];
for (int i = len - 2; i >= 0; i--){
res[i] *= right;
right *= nums[i];
}
return res;
}
Reference
https://leetcode.com/problems/product-of-array-except-self/description/