- Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path015-3sum.py
39 lines (35 loc) · 1.1 KB
/
015-3sum.py
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
"""
Problem Link: https://leetcode.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
"""
classSolution:
defthreeSum(self, nums: List[int]) ->List[List[int]]:
res= []
nums.sort()
foriinrange(len(nums)-2):
ifi==0ornums[i] >nums[i-1]:
start=i+1
end=len(nums)-1
whilestart<end:
Sum=nums[i] +nums[start] +nums[end]
ifSum==0:
res.append([nums[i],nums[start],nums[end]])
ifSum<0:
curStart=nums[start]
whilecurStart==nums[start] andstart<end:
start+=1
else:
curEnd=nums[end]
whilecurEnd==nums[end] andstart<end:
end-=1
returnres