class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
n = len(nums)
res = []
if not nums or n < 4:
return res
for out_l in range(n-3):
if out_l > 0 and nums[out_l] == nums[out_l-1]:
continue
s = nums[out_l] + nums[out_l+1] + nums[out_l+3] + nums[out_l+2]
if s > target:
break
s = nums[out_l] + nums[n-1] + nums[n-2] + nums[n-3]
if s < target:
continue
for out_r in range(out_l+1, n-2):
if out_r > out_l+1 and nums[out_r] == nums[out_r-1]:
continue
s = nums[out_l] + nums[out_r] + nums[out_r+1] + nums[out_r+2]
if s > target:
break
s = nums[out_l] + nums[out_r] + nums[n-1] + nums[n-2]
if s < target:
continue
in_l = out_r + 1
in_r = n - 1
while in_l < in_r:
s = nums[out_l] + nums[out_r] + nums[in_l] + nums[in_r]
if s == target:
res.append([nums[out_l], nums[out_r], nums[in_l], nums[in_r]])
while in_l < in_r and nums[in_l] == nums[in_l+1]:
in_l += 1
in_l += 1
while in_l < in_r and nums[in_r] == nums[in_r-1]:
in_r -= 1
in_r -= 1
elif s > target:
in_r -= 1
else:
in_l += 1
return res