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