給定長度為 n 的整數(shù)數(shù)組 nums趟据,其中 n > 1,返回輸出數(shù)組 output 术健,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘積汹碱。
示例:
輸入: [1,2,3,4]
輸出: [24,12,8,6]
說明: 請不要使用除法,且在 O(n) 時間復(fù)雜度內(nèi)完成此題荞估。
進(jìn)階:
你可以在常數(shù)空間復(fù)雜度內(nèi)完成這個題目嗎咳促?( 出于對空間復(fù)雜度分析的目的稚新,輸出數(shù)組不被視為額外空間。)
class Solution {
public int[] productExceptSelf(int[] nums) {
//當(dāng)前位置左邊數(shù)的乘積*當(dāng)前位置右邊數(shù)的乘積
int len = nums.length;
int[] re = new int[len];
if(len == 0) return new int[]{0};
int help = 1;
for(int i = 0; i < len; i++){
re[i] = help;
help *= nums[i];
}
help = 1;
for(int i = len-1; i >= 0; i--){
re[i] *= help;
help *= nums[i];
}
return re;
}
}