您的位置:首页 > 其它

LeetCode-Product of Array Except Self

2015-07-31 10:18 190 查看
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.)

自己没倒腾出来,确实挺难想的,但是当得知其中的奥秘时,不时感觉此算法真是妙。

题目大致意思就是求一个output数组,output[i]为数组nums数组除nums[i]之外数字的所有乘积,比如:

Input : [1, 2, 3, 4, 5]
Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)]
= [120, 60, 40, 30, 24]

要求不用除法,时间复杂度O(n)

解题思路基于以下集合

{              1,         a[0],    a[0]*a[1],    a[0]*a[1]*a[2],  }
{ a[1]*a[2]*a[3],    a[2]*a[3],         a[3],                 1,  }

很显然,这两个集合都可以在O(n)的时间复杂度求得,之后两个集合对应位置相乘即为所得。是不是很妙?

空间复杂度为O(n)的实现:

public int[] productExceptSelf(int[] nums) {
int[] productBelow = new int[nums.length];
int n = 1;
for (int i = 0; i < nums.length; i++) {
productBelow[i] = n;
n *= nums[i];
}

int[] productAbove = new int[nums.length];
n = 1;
for (int i = nums.length-1; i >= 0; i--) {
productAbove[i] = n;
n *= nums[i];
}

int[] output = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
output[i] = productAbove[i] * productBelow[i];
}
return output;
}
但是,如果要求是O(1)的空间复杂度呢?只需要把最后两步合二为一即可:

int[] output = new int[nums.length];
int n = 1;
for (int i = 0; i < nums.length; i++) {
output[i] = n;
n *= nums[i];
}

n = 1;
for (int i = nums.length-1; i >= 0; i--) {
output[i] *= n;
n *= nums[i];
}
return output;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: