Skip to content

Commit 5f5c260

Browse files
author
weiy
committed
product of array except self medium
1 parent 3345176 commit 5f5c260

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Array/ProductOfArrayExceptSelf.py

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
3+
4+
Example:
5+
6+
Input: [1,2,3,4]
7+
Output: [24,12,8,6]
8+
Note: Please solve it without division and in O(n).
9+
10+
Follow up:
11+
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
12+
13+
给一个数组,返回数组中除了这一位的数其他数的乘积。
14+
15+
不能用除的,且时间复杂度需要为 O(n)。
16+
17+
进阶条件 空间复杂度为常数级别。
18+
19+
一刷进阶条件没达成。
20+
21+
基本思路是,一左一右两个存储位置的新列表。
22+
23+
从左到右过一遍,从右到左过一遍。算出每个数左边和右边的乘积。
24+
25+
最后输出每个位置的左*右。
26+
27+
效率是 O(n),没用除。但空间是 O(2n)。
28+
29+
beat 57% ~ 80% (在 2 中需要把 range 变为 xrange).
30+
前面那几个的思路也是同样的。多测几次应该也能beat 100%...
31+
32+
哎哎?突然想到,output 的数组不算在额外空间里的话,
33+
可以直接把output数组作为 left。然后right的时候直接替换就好了啊。
34+
35+
没错,这样就是 O(1) 了,进阶达成。
36+
37+
beat 98%。
38+
39+
测试链接:
40+
https://leetcode.com/problems/product-of-array-except-self/description/
41+
42+
"""
43+
class Solution(object):
44+
def productExceptSelf(self, nums):
45+
"""
46+
:type nums: List[int]
47+
:rtype: List[int]
48+
"""
49+
output = [1]
50+
for i in range(len(nums)-1):
51+
output.append(output[-1] * nums[i])
52+
53+
right = 1
54+
for i in range(len(nums)-1, -1, -1):
55+
output[i] = right * output[i]
56+
right *= nums[i]
57+
58+
return output
59+
60+
# left = [1]
61+
# right = [1]
62+
63+
64+
# for i in range(len(nums)-1):
65+
# left.append(left[-1] * nums[i])
66+
67+
# for i in range(len(nums)-1, 0, -1):
68+
# right.append(right[-1] * nums[i])
69+
70+
# length = len(left)
71+
72+
# return [left[i] * right[length-1-i] for i in range(length)]

0 commit comments

Comments
 (0)