最近放暑假了。昨天回家坐了一晚上绿皮火车人都要废掉,今日再做
话不多说,放题
给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/product-of-array-except-self
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例:
输入: [1,2,3,4]
输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
华丽丽的分割线---------------------------------------------------------------------------------------------------------------------------
分析:
因为不能使用除法,且复杂度规定为O(N),因此必定要保存累积的乘积
如:
f(n) = f(0)*f(1)*f(2)*......f(n-1) (其中,当n=0或者n时,f(n) = 1。n为nums.length-1)
因此,可以使用循环的方法,使用两个额外的数组,分别保存k处为止左边与右边累积的乘积
f(k) = f(0)*f(1)*...*f(k-1)*f(k+1)*f(k+2)*...*f(n) 分成两边
则k处的结果就是这两个额外数组的乘积即可.
贴代码:
static public int[] productExceptSelf(int[] nums) {
int []res1 = new int[nums.length];
int []res2 = new int[nums.length];
int index1 = 0;
int index2 = nums.length-1;
while(index1 < nums.length) {
if(index1 == 0)
res1[index1] = 1;
else
res1[index1] = res1[index1-1]*nums[index1-1];
index1++;
}
while(index2 >= 0) {
if(index2 == nums.length-1) {
res2[index2] = 1;
}else {
res2[index2] = res2[index2+1]*nums[index2+1];
}
index2--;
}
for(int i = 0;i < nums.length;i++) {
nums[i] = res1[i]*res2[i];
}
for(int e: nums)
System.out.print(e+" ");
return nums;
}