-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.py
50 lines (50 loc) · 1.71 KB
/
15.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
40
41
42
43
44
45
46
47
48
49
50
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 3:
return []
res = []
nums.sort()
first = 0
second = 1
third = len(nums) - 1
while second < third:
if nums[first] + nums[second] + nums[third] == 0:
res.append([nums[first], nums[second], nums[third]])
temp = nums[second]
while second < third:
if temp == nums[second]:
second += 1
else:
break
elif nums[first] + nums[second] + nums[third] < 0:
second += 1
else:
third -= 1
for first in range(1, len(nums) - 2):
if nums[first] > 0:
break
if nums[first] == nums[first - 1]:
continue
else:
second = first + 1
third = len(nums) - 1
while second < third:
if nums[third] < 0:
break
if nums[first] + nums[second] + nums[third] == 0:
res.append([nums[first], nums[second], nums[third]])
third -= 1
while second < third:
if nums[third + 1] == nums[third]:
third -= 1
else:
break
elif nums[first] + nums[second] + nums[third] < 0:
second += 1
else:
third -= 1
return res