Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0. A solution set is: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]My code:
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
n = len(nums)
result = []
nums.sort()
for i in range(n-3):
if nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target:
break
if i ==0 or (i>0 and nums[i]!=nums[i-1]):
for j in range(i+1,n-2):
if nums[i]+nums[j]+nums[j+1]+nums[j+2]>target:
break
low = j+1
high = n-1
while low<high:
if nums[low]+nums[high]==target-nums[i]-nums[j] and [nums[i],nums[j],nums[low],nums[high]] not in result:
result.append([nums[i],nums[j],nums[low],nums[high]])
while (low < high and nums[low] == nums[low+1]):
low+=1
while (low < high and nums[high] == nums[high-1]):
high-=1
low +=1
high-=1
elif nums[low]+nums[high]>target-nums[i]-nums[j]:
while (low < high and nums[high] == nums[high-1]):
high-=1
high -=1
else:
while (low < high and nums[low] == nums[low+1]):
low+=1
low +=1
return result