LeetCode[Array]---- 4Sum

 4Sum

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

分析:

3Sum这类题目的升级版。题目要求给定一个数组nums,从中找到所有的不重复的四个元素a,b,c,d,使得a + b + c + d的和等于target。

依旧是借助3Sum题目的思路。依旧是对数组进行排序,然后使用双指针进行遍历,不一样的是,对于四个元素的情况,需要在三个元素的情况之上多一层循环。

具体的,我们把排序好的数组分成三个不相交部分P1, P2,P3,从P1中选择一个元素a,从P2中选择另一个元素b,然后使用双指针由前往后和由后往前的选择元素c和d,如果a + b + c + d的和nsum等于target,则记录此时的abcd;如果nsum大于target,则右指针向左移动,减少nsum值;如果nsum小于target,那么左指针向右移动,增加nsum值。

另外,对于所有的解需要进行去重。具体可以判断每次选择的元素是否与前一次选择的元素相同,如果相同则跳过不选。


相应的代码为:

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        nums.sort()
        nums_len = len(nums)
        res = []
        for i in range(nums_len - 3):
            if i and nums[i] == nums[i - 1]:
                continue
            for j in range(i+1, nums_len - 2):
                left = j + 1
                right = nums_len - 1
                if j != i + 1 and nums[j] == nums[j-1]:
                    continue
                while left < right:
                    nsums = nums[i] + nums[j] + nums[left] + nums[right]
                    if nsums == target:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        while left < right and nums[left+1] == nums[left]:
                            left += 1
                        while left < right and nums[right-1] == nums[right]:
                            right -= 1
                        left += 1
                        right -= 1
                    elif nsums > target:
                        right -= 1
                    else:
                        left += 1
        return res

猜你喜欢

转载自blog.csdn.net/whiterbear/article/details/51188662