Skip to content

Commit 2de0585

Browse files
author
ironartisan
committed
添加0018.四数之和双指针法python3版本
1 parent 82e73de commit 2de0585

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

problems/0018.四数之和.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,33 @@ class Solution {
167167

168168
Python:
169169
```python
170-
170+
# 双指针法
171+
class Solution:
172+
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
173+
174+
nums.sort()
175+
n = len(nums)
176+
res = []
177+
for i in range(n):
178+
if i > 0 and nums[i] == nums[i - 1]: continue
179+
for k in range(i+1, n):
180+
if k > i + 1 and nums[k] == nums[k-1]: continue
181+
p = k + 1
182+
q = n - 1
183+
184+
while p < q:
185+
if nums[i] + nums[k] + nums[p] + nums[q] > target: q -= 1
186+
elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
187+
else:
188+
res.append([nums[i], nums[k], nums[p], nums[q]])
189+
while p < q and nums[p] == nums[p + 1]: p += 1
190+
while p < q and nums[q] == nums[q - 1]: q -= 1
191+
p += 1
192+
q -= 1
193+
return res
194+
```
195+
```python
196+
# 哈希表法
171197
class Solution(object):
172198
def fourSum(self, nums, target):
173199
"""

0 commit comments

Comments
 (0)