原题链接:238. Product of Array Except Self
【思路-Java、Python】
根据Note: The output array does not count as extra space for the purpose of space complexity analysis.
我们还是可以申请大小为 n 的空间 result 用于返回结果,由于题目要求不能出现除运算,所以本题的基本思路是:
0. 申请两个大小为 n 的数组
1. 第一个数组的第 i 个元素存储第0个到第 i-1 个元素的乘积
2. 第二个数组的第 i 个元素存储第 i+1 到最后一个元素的乘积
3. 然后将两个数组的第 i 个元素和第 i 个元素相乘就能得到结果
进行优化发现其实用一个 mul 变量就可以将2数组优化为只使用1个数组
以[2,3,4]为例:
①之后 result = [1, 2, 6]
②之后 result = [12, 8, 6], mul = 24
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
result[0] = 1;
for (int i = 1; i < nums.length; i++) //①
result[i] = result[i - 1] * nums[i - 1];
for (int i = nums.length - 2, mul = nums[i+1]; i >= 0; i--) { //②
result[i] *= mul;
mul *= nums[i];
}
return result;
}
}
17 / 17
test cases passed. Runtime: 2 ms Your runtime beats 46.07% of javasubmissions.
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [1] * len(nums)
for i in range(1,len(nums)) :
result[i] = result[i - 1] * nums[i - 1];
mul = 1;
for i in range(0,len(nums))[::-1] :
result[i] *= mul
mul *= nums[i]
return result
17 / 17
test cases passed. Runtime: 184 ms
Your runtime beats 42.64% of pythonsubmissions.
536

被折叠的 条评论
为什么被折叠?



