mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0018.四数之和.md
This commit is contained in:
@ -207,35 +207,40 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
(版本一) 双指针
|
||||||
```python
|
```python
|
||||||
# 双指针法
|
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
|
||||||
class Solution:
|
result = []
|
||||||
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
|
|
||||||
|
|
||||||
nums.sort()
|
nums.sort()
|
||||||
n = len(nums)
|
for k in range(len(nums)):
|
||||||
res = []
|
if nums[k] > target and nums[k] >= 0:
|
||||||
for i in range(n):
|
break
|
||||||
if i > 0 and nums[i] == nums[i - 1]: continue # 对nums[i]去重
|
if k > 0 and nums[k] == nums[k-1]:
|
||||||
for k in range(i+1, n):
|
continue
|
||||||
if k > i + 1 and nums[k] == nums[k-1]: continue # 对nums[k]去重
|
for i in range(k+1, len(nums)):
|
||||||
p = k + 1
|
if nums[k] + nums[i] > target and nums[k] + nums[i] >= 0:
|
||||||
q = n - 1
|
break
|
||||||
|
if i > k+1 and nums[i] == nums[i-1]:
|
||||||
while p < q:
|
continue
|
||||||
if nums[i] + nums[k] + nums[p] + nums[q] > target: q -= 1
|
left, right = i+1, len(nums)-1
|
||||||
elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
|
while right > left:
|
||||||
|
if nums[k] + nums[i] + nums[left] + nums[right] > target:
|
||||||
|
right -= 1
|
||||||
|
elif nums[k] + nums[i] + nums[left] + nums[right] < target:
|
||||||
|
left += 1
|
||||||
else:
|
else:
|
||||||
res.append([nums[i], nums[k], nums[p], nums[q]])
|
result.append([nums[k], nums[i], nums[left], nums[right]])
|
||||||
# 对nums[p]和nums[q]去重
|
while right > left and nums[right] == nums[right-1]:
|
||||||
while p < q and nums[p] == nums[p + 1]: p += 1
|
right -= 1
|
||||||
while p < q and nums[q] == nums[q - 1]: q -= 1
|
while right > left and nums[left] == nums[left+1]:
|
||||||
p += 1
|
left += 1
|
||||||
q -= 1
|
right -= 1
|
||||||
return res
|
left += 1
|
||||||
|
return result
|
||||||
```
|
```
|
||||||
|
(版本二) 使用字典
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# 哈希表法
|
|
||||||
class Solution(object):
|
class Solution(object):
|
||||||
def fourSum(self, nums, target):
|
def fourSum(self, nums, target):
|
||||||
"""
|
"""
|
||||||
|
Reference in New Issue
Block a user