-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4sum.py
39 lines (36 loc) · 1.21 KB
/
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
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
l = len(nums)
h = 0
while h < l - 3:
a = nums[h]
i = h + 1
while i < l - 2:
b = nums[i]
j = i + 1
k = l - 1
while j < k:
c = nums[j]
d = nums[k]
temp_4_sum = a + b + c + d
if temp_4_sum == target:
res.append([a, b, c, d])
elif temp_4_sum > target:
while nums[k] == d and k > j:
k -= 1
continue
elif temp_4_sum < target:
while nums[j] == c and j < k:
j += 1
continue
while nums[k] == d and j < k:
k -= 1
while nums[j] == c and j < k:
j += 1
while nums[i] == b and i < l - 2:
i += 1
while nums[h] == a and h < l - 3:
h += 1
return res