[LeetCode]18. 4Sum

18. 4Sum

思路:先排序(要使用Two Pointers必须排序),然后选择两个结点,剩下的两个结点通过Two Pointers来决定。

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
        
posted @ 2017-08-19 03:07  banananana  阅读(123)  评论(0)    收藏  举报