[LeetCode]18. 4Sum
18. 4Sum
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
def two_point(nums, t):
left, right = 0, len(nums)-1
res = []
while left < right:
s = nums[left] + nums[right]
if s < t:
left += 1
elif s > t:
right -= 1
else:
res.append([nums[left], nums[right]])
while left < right and nums[left] == nums[left+1]:
left += 1
while left < right and nums[right] == nums[right-1]:
right -= 1
left += 1
right -= 1
return res
result = []
nums.sort()
for i in xrange(0, len(nums)):
for j in xrange(i+1, len(nums)):
neg = target - (nums[i] + nums[j])
if len(nums[j+1:]) >= 2:
twos = two_point(nums[j+1:], neg)
for x in twos:
x.extend([nums[i], nums[j]])
if x not in result:
result.append(x)
return result
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号