-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15.三数之和.py
35 lines (35 loc) · 972 Bytes
/
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
#
# @lc app=leetcode.cn id=15 lang=python3
#
# [15] 三数之和
#
# %%
# @lc code=start
class Solution:
def threeSum(self, nums):
n = len(nums)
res = []
if n < 3:
return []
nums.sort()
for i in range(n):
if (i > 0 and nums[i] == nums[i-1]):
continue
low = i+1
high = n-1
while low < high:
target = nums[i]+nums[low]+nums[high]
if target == 0:
res.append([nums[i], nums[low], nums[high]])
while(low < high and nums[low] == nums[low+1]):
low += 1
while(low < high and nums[high] == nums[high-1]):
high -= 1
# low+=1
# high -=1
if target < 0:
low += 1
else:
high -= 1
return res
# @lc code=end