【LeetCode】【18.4sum】(python版)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_20141867/article/details/80946272

Description:

Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [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]
]

有了前面3sum的经验,本题很容易联想到一种思路是:仍然固定一个数a,使用3sum的算法求 b + c + d = target - a。这样只需要在3sum算法基础上稍微修改,并在最外层加一个循环,时间复杂度为 O ( n 3 ) O(n^3)

class Solution(object):
    def threeSum(self, nums, target):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        n = len(nums)
        for i in range(n-2):
            if i > 0 and nums[i] == nums[i-1]: continue
            low = i + 1
            high = n - 1
            while low < high:
                cursum = nums[low] + nums[high] + nums[i]
                if cursum == target:
                    res.append([nums[i], nums[low], nums[high]])
                    while low < high and nums[low] == nums[low+1]:
                        low = low + 1
                    while low < high and nums[high] == nums[high-1]:
                        high = high - 1
                    high = high - 1
                    low = low + 1
                elif cursum > target:
                    high = high - 1
                else:
                    low = low + 1
        return res


    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in range(len(nums) - 3):
            if i > 0 and nums[i] == nums[i - 1]: continue
            curres = self.threeSum(nums[i+1:], target - nums[i])
            if len(curres) > 0:
                for curarr in curres:
                    curarr.append(nums[i])
                    res.append(curarr[:])
        return res

第二种思路是先将数组两两求和保存结果S,在求和结果基础上进行3Sum计算,即求解 S 1 + c + d = t a r g e t S_1+c+d=target 。需要注意的是,保存求和结果时也一并保存两数下标,避免重复计算。

class Solution(object):
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        from collections import defaultdict
        numLen, res, two_sum= len(nums), set(), defaultdict(list)
        if numLen < 4: return []
        nums.sort()
        for p in range(numLen):
            for q in range(p + 1, numLen):
                two_sum[nums[p] + nums[q]].append((p, q))
        for i in range(numLen):
            for j in range(i + 1, numLen - 2):
                T = target - nums[i] - nums[j]
                if T in two_sum:
                    for k in two_sum[T]:
                        if k[0] > j: res.add((nums[i], nums[j], nums[k[0]], nums[k[1]]))
        return [list(i) for i in res]

猜你喜欢

转载自blog.csdn.net/qq_20141867/article/details/80946272