-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC_15.py
38 lines (26 loc) · 869 Bytes
/
LC_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
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
ans = []
nums.sort()
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = len(nums) - 1
while j < k:
s = nums[i] + nums[j] + nums[k]
if s == 0:
triplet = [nums[i], nums[j], nums[k]]
ans.append(triplet)
while j < k and nums[j] == nums[j + 1]:
j += 1
j += 1
while j < k and nums[k] == nums[k - 1]:
k -= 1
k -= 1
if s < 0:
j += 1
if s > 0:
k -= 1
return ans