-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path018-4sum.py
61 lines (49 loc) · 1.75 KB
/
018-4sum.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
"""
四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
#### 注意:
答案中不可以包含重复的四元组。
#### 示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
"""
def four_sum(nums, target: int):
if len(nums) < 4:
return []
nums.sort()
ans, n = [], len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target:
continue
left, right = j + 1, n - 1
while left < right:
total = nums[i] + nums[j] + nums[left] + nums[right]
if total == target:
a = [nums[i], nums[j], nums[left], nums[right]]
if a not in ans:
ans.append(a)
left += 1
right -= 1
elif total < target:
left += 1
else:
right -= 1
return ans
if __name__ == '__main__':
print(four_sum([1, 0, -1, 0, -2, 2], 0))