-
Notifications
You must be signed in to change notification settings - Fork 0
/
threeSum.py
65 lines (56 loc) · 1.81 KB
/
threeSum.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : threeSum.py
@Time : 2024/09/24 15:35:33
@Author : Zihao Zheng
@Email : [email protected]
'''
'''
哈希法 双指针
'''
class Solution():
def threeSum(self,nums:list[int])->list[list[int]]:
result=[]
nums.sort()
for i in range(len(nums)):
if nums[i]>0:
break
if i>0 and nums[i]==nums[i-1]: #a 去重
continue
d={}
for j in range(i+1,len(nums)):
if j>i+2 and nums[j]==nums[j-1]==nums[j-2]: #b 去重
continue
c=0-(nums[i]+nums[j])
if c in d:
result.append([nums[i],nums[j],c])
d.pop(c) #c 去重
else:
d[nums[j]]=j
return result
def threeSum(self,nums:list[int])->list[list[int]]:
result=[]
nums.sort()
for i in range(len(nums)):
if nums[i]>0:
break
if i>0 and nums[i]==nums[i-1]: #a 去重
continue
left=i+1
right=len(nums)-1
while right>left:
sum_=nums[i]+nums[left]+nums[right]
if sum_<0:
left+=1
elif sum_>0:
right-=1
else:
result.append[nums[i],nums[left],nums[right]]
while right>left and nums[right]==nums[right-1]:
right-=1
while right>left and nums[left]==nums[left+1]:
left+=1
right-=1
left+=1
return result