-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path4. 4SumLeet.py
33 lines (32 loc) · 1.08 KB
/
4. 4SumLeet.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
class Solution:
def fourSum(self, nums: [int], target: int) -> [[int]]:
nums.sort()
n = len(nums)
ans = []
for i in range(n):
if i > 0 and nums[i] == nums[i-1]:
continue
for j in range(i+1, n):
if j != i+1 and nums[j] == nums[j-1]:
continue
k = j+1
l = n-1
while k<l:
s = nums[i]
s += nums[j]
s += nums[k]
s += nums[l]
if s == target:
ans.append([nums[i], nums[j], nums[k], nums[l]])
l -= 1
k += 1
while (k<l and nums[k] == nums[k-1]):
k+=1
while (k<l and nums[l] == nums[l+1]):
l-=1
elif s > target:
l-=1
else:
k+=1
return ans
# Link: https://leetcode.com/problems/4sum/