4 sum

问题:给定一个数组和一个目标值,输出数组中所有的4个数之和为目标值的可能组合

解决思路:先排序,再固定其中两个值,对另外两个值进行遍历

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        length = len(nums)
        if length < 4:
            return []
        out = []
        nums.sort()
        for i in range(length-3):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            for j in range(i+1,length-2):
                if j > i+1 and nums[j] == nums[j-1]:
                    continue
                expect_two_sum = target-nums[i]-nums[j]
                l = j+1
                r = length-1
                while l < r:
                    two_sum = nums[l] + nums[r]
                    if two_sum > expect_two_sum or (r < length-1 and nums[r]==nums[r+1]):
                        r -= 1
                    elif two_sum < expect_two_sum or (l > j + 1 and nums[l] == nums[l-1]):
                        l += 1
                    else:
                        out.append([nums[i],nums[j],nums[l],nums[r]])
                        l += 1
                        r -= 1
        return out

 

posted @ 2019-03-25 12:57  秦qin  阅读(131)  评论(0编辑  收藏  举报