1. 程式人生 > >LeetCode[Array]---- 4Sum

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