描述
给定一个长度为 n 的数组 nums ,返回一个数组 res,res[i]是nums数组中除了nums[i]本身以外其余所有元素的乘积,即:res[i] = nums[1] \times nums[2] \times …\times nums[i-1] \times nums[i+1] … \times nums[n] \res[i]=nums[1]×nums[2]×…×nums[i−1]×nums[i+1]…×nums[n]
1.请不要使用除法,并且在 O(n) 时间复杂度内完成此题。
2.题目数据保证res数组的元素都在 32 位整数范围内
3.有O(1)空间复杂度的做法,返回的res数组不计入空间复杂度计算
分析
暴力遍历的时间复杂度是O(n^2),可以选择建立两个辅助数组来实现O(n)的效果。
一个数组记录当前元素之前的乘积,另一个记录当前元素之后所有元素的乘积。
这样空间复杂度是O(n),但通过修改原数组nums可以实现O(1)的效果。
import java.util.*;
public class Solution {
public int[] timesExceptSelf (int[] nums) {
int[] ans = new int[nums.length];
ans[0] = 1;
for(int i = 1; i < nums.length; i++){
ans[i] = ans[i-1] * nums[i-1];
}
int pre = nums[nums.length - 1];
nums[nums.length - 1] = 1;
for(int i = nums.length - 2; i >= 0; i--){
int tmp = nums[i];
nums[i] = nums[i+1] * pre;
pre = tmp;
}
for(int i = 0; i < nums.length; i++){
ans[i] *= nums[i];
}
return ans;
}
}