problem
just like the title.
algorithm
Enumerate the first two number, then get two numbers whose sum is closed to the target number minus the first number.
code
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
ans = []
sNum = len(nums)
for a in range(sNum):
if a and nums[a] == nums[a-1]:
continue
for b in range(a+1, sNum):
if b > a+1 and nums[b] == nums[b-1]:
continue
c = b+1
d = sNum-1
while c < d:
if c > b+1 and nums[c] == nums[c-1] or nums[a] + nums[b] + nums[c] + nums[d] < target:
c += 1
elif nums[a] + nums[b] + nums[c] + nums[d] == target:
ans.append([nums[a], nums[b], nums[c], nums[d]])
c += 1
else:
d -= 1
return ans