-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15-ThreeSum.py
More file actions
51 lines (40 loc) · 1.56 KB
/
15-ThreeSum.py
File metadata and controls
51 lines (40 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Python3
# 时间复杂度:O(N^2) 空间复杂度:O(logN)
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
nums.sort()
ans = list()
# a + b + c = 0
# 枚举 a
for first in range(n):
# 需要和上一次枚举的数不相同
if first > 0 and nums[first] == nums[first - 1]:
continue
# c 对应的指针初始指向数组的最右端
third = n - 1
target = - nums[first]
# 枚举 b
for second in range(first + 1, n):
# 需要和上一次枚举的数不相同
if second > first + 1 and nums[second] == nums[second - 1]:
continue
# 需要保证 b 的指针在 c 的指针的左侧
while second < third and nums[second] + nums[third] > target:
third -= 1
# 如果指针重合,随着 b 后续的增加就不会存在满足 a + b + c = 0 并且 b < c 的 c, 可以退出循环
if second == third:
break
if nums[second] + nums[third] == target:
ans.append([nums[first], nums[second], nums[third]])
return ans
def main():
test = Solution()
#nums = [-1,0,1,2,-1,-4]
#nums = [0,0,0,0]
nums = [-1,0,1,2,-1,-4,-2,-3,3,0,4]
res = test.threeSum(nums)
print(res)
if __name__ == "__main__":
main()