public class Solution {
public int[] ProductExceptSelf(int[] nums) {
int[] result = new int[nums.Length];
for (int i = , tmp = ; i < nums.Length; i++)
{
result[i] = tmp;
tmp *= nums[i];
}
for (int i = nums.Length - , tmp = ; i >= ; i--)
{
result[i] *= tmp;
tmp *= nums[i];
}
return result;
}
}
https://leetcode.com/problems/product-of-array-except-self/#/description
在第一个循环中,记录当前的索引左侧的数字乘积,和当前的索引右侧的数字乘积。然后两部分乘积相乘,这样的思路比较简单,但是时间复杂度是O(n*n)。
本题的解法时间复杂度更低,但是代码不容易理解。
补充一个python的实现:
class Solution:
def productExceptSelf(self, nums: 'List[int]') -> 'List[int]':
n = len(nums)
front = [1] * n
front[0] = nums[0] back = [1] * n
back[n-1] = nums[n-1] for i in range(1,n):
front[i] = front[i-1] * nums[i] for i in range(n-2,0,-1):
back[i] = back[i+1] * nums[i] l = list()
for i in range(n):
if i == 0:
f = 1
b = back[i+1]
l.append(f*b)
elif i == n-1:
f = front[i-1]
b = 1
l.append(f*b)
else:
f = front[i-1]
b = back[i+1]
l.append(f*b)
return l