一、題目描述
給定長度爲 n 的整數數組 nums,其中 n > 1,返回輸出數組 output ,其中 output[i] 等於 nums 中除 nums[i] 之外其餘各元素的乘積。
示例:
輸入: [1,2,3,4]
輸出: [24,12,8,6]
說明: 請不要使用除法,且在 O(n) 時間複雜度內完成此題。
進階:
你可以在常數空間複雜度內完成這個題目嗎?( 出於對空間複雜度分析的目的,輸出數組不被視爲額外空間。)
二、解題思路
可以分兩步進行,先計算出該數左邊的乘積,再計算右邊的乘積,最後再乘起來即可。
三、java代碼
class Solution {
public int[] productExceptSelf(int[] nums) {
//思路:當前數左邊的乘積 * 當前數右邊的乘積
int [] res = new int[nums.length];
int temp = 1;
for(int i=0;i<nums.length;i++){
res[i] = temp;
temp *= nums[i];
}
temp = 1;
for(int i=nums.length-1;i>=0;i--){
res[i] *= temp;
temp *= nums[i];
}
return res;
}
}