Description:
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.)
題目描述:
- 給定一個數組,對數組中的每個元素求除自身外的其他元素的乘積
- 比如:給定 [1,2,3,4], 返回結果 [24,12,8,6].
注意事項:
- 不能使用除法
- 使用固定的額外空間
- O(n)效率
思考過程:
- 如果題目沒有加O(n)條件的話,可以使用循環嵌套暴力求解,但是效率非常低
- 如果沒有限制不能使用除法,可以先循環一次計算所有元素乘積,再次循環用乘積去除當前元素再進行替換,這樣就非常簡單,但是可能存在值為0的元素,這時候需要區分對待
- 當沒有0的時候,直接進行除就可以了。
- 當只有一個0的時候,為0的那位元素替換為其他元素的乘積,其他元素替換為0。
- 當0的數量大于等于2的時候,排除任何一個元素都會存在與0相乘的情況,所以全部替換為0即可。
- 加上以上兩個條件之后,需要重新考慮了。可以想到,每個位置的元素結果應該為其左側所有元素乘積再乘其右側所有元素乘積,所以現在需要考慮如何分別獲取并儲存每個元素兩側元素的乘積結果。
代碼:
class Solution {
public int[] productExceptSelf(int[] nums) {
int N = nums.length;
int[] res = new int[N]; //創建一個額外空間,用于存儲獲取到的兩側元素乘積結果
int l = 1;
for(int i = 0; i < N ; i++){ //先進行循環,獲取每個元素左側元素的乘積
res[i] = l; //l用于保存每個元素左側元素乘積結果
l *= nums[i]; //獲取下一次需要的值
}
int r = 1;
for(int i = N-1; i >= 0 ; i--){ //再次循環,獲取當前位置對應元素的右側元素乘積,然后把獲取到的結果進行修改
res[i] *= r; //r值用于保存每個元素右側的元素乘積,本身res最后一位就是
r *= nums[i]; //獲取到乘積之后進行修改
}
return res; //返回最終結果
}
}