ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

LeetCode 238. Product of Array Except Self

LeetCode 238. Product of Array Except Self

题目:

Given an arraynumsofnintegers wheren> 1, return an arrayoutputsuch thatoutput[i]is equal to the product of all the elements ofnumsexceptnums[i].

Example:

Input:[1,2,3,4]Output:[24,12,8,6]

Constraint:It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.

Note:Please solve itwithout divisionand in O(n).

Follow up:
Could you solve it with constant space complexity? (The output arraydoes notcount as extra space for the purpose of space complexity analysis.)


先写了个用除法的版本,其实还是有些corner case要注意的,比如如果数组中出现了0。出现0还分两种情况,如果只出现了一次,那只有在它那里的result不是0,如果超过一次,那就全是0了。

Runtime: 1 ms, faster than 99.99% of Java online submissions for Product of Array Except Self.

Memory Usage: 47.3 MB, less than 96.15% of Java online submissions for Product of Array Except Self.

class Solution { public int[] productExceptSelf(int[] nums) { int all = 1; int zeroCount = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0) { zeroCount++; } else { all *= nums[i]; } } int[] result = new int[nums.length]; if (zeroCount > 1) { return result; } for (int i = 0; i < nums.length; i++) { if (zeroCount == 0) { result[i] = all / nums[i]; } else { if (nums[i] == 0) { result[i] = all; } else { result[i] = 0; } } } return result; } }

然后是不用除法的做法。我们可以把整个数组分成两半,left,nums[i],和right。分别求出左半边和右半边乘积,最后相乘就是了。具体的左半边和右半边可以用数组表示,left[i]表示从[0, i - 1]的乘积,right[i]表示[i + 1, len - 1]的乘积。写代码的时候需要注意下标,首先要将left[0]和right[len - 1]初始化成1,然后再for循环里更新left[i]和right[len - i - 1],注意left[i]的乘积是要left[i - 1]乘i - 1,right也同理。

Runtime: 2 ms, faster than 32.44% of Java online submissions for Product of Array Except Self.

Memory Usage: 47.7 MB, less than 80.91% of Java online submissions for Product of Array Except Self.

class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length; int[] left = new int[len]; left[0] = 1; int[] right = new int[len]; right[len - 1] = 1; for (int i = 1; i < len; i++) { left[i] = left[i - 1] * nums[i - 1]; right[len - i - 1] = right[len - i] * nums[len - i]; } int[] result = new int[len]; for (int i = 0; i < len; i++) { result[i] = left[i] * right[i]; } return result; } }

2026.10.20

时隔无数年也是一点儿不会做。思路就是上面写的,把这个乘积分成左边的和右边的。但是其实不需要用额外的数组来存放,只需要两个变量存左边到现在的乘积,和右边到现在的乘积,以及最后的输出数组就行。两个for loop。但是自己在写的时候边界条件和顺序还是有点迷糊,需要复习。

class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; int left = 1; for (int i = 0; i < nums.length; i++) { result[i] = left; left *= nums[i]; } int right = 1; for (int i = nums.length - 1; i >= 0; i--) { result[i] *= right; right *= nums[i]; } return result; } }
返回列表