moonlightshadow123
6/21/2017 - 9:41 AM

18. 4Sum

  1. 4Sum
class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        self.res = []
        nums = sorted(nums)
        firstIndex = 0
        # The outer while loop
        while firstIndex <= len(nums) - 4:
            secondIndex = firstIndex + 1
            # The inner while loop
            while secondIndex <= len(nums) - 3:
                self.twoSum(nums, firstIndex, secondIndex, target)
                secondIndex += 1
                while nums[secondIndex] == nums[secondIndex - 1] and secondIndex <= len(nums) - 3:
                    secondIndex += 1
            firstIndex += 1
            while nums[firstIndex] == nums[firstIndex - 1] and firstIndex <= len(nums) - 4:
                firstIndex += 1
        return self.res
        
    def twoSum(self, nums, firstIndex, secondIndex, target):
        beginIndex = secondIndex + 1
        endIndex = len(nums) - 1
        while beginIndex < endIndex:
            curSum = nums[firstIndex]+nums[secondIndex]+nums[beginIndex]+nums[endIndex]
            if curSum == target:
                self.res.append([nums[firstIndex], nums[secondIndex],nums[beginIndex],nums[endIndex]])
                beginIndex += 1
                endIndex -= 1
                while nums[beginIndex] == nums[beginIndex - 1] and beginIndex < endIndex:
                    beginIndex += 1
                while nums[endIndex] == nums[endIndex + 1] and beginIndex < endIndex:
                    endIndex -= 1
            elif curSum < target:
                beginIndex += 1
            else:
                endIndex -= 1

https://leetcode.com/problems/4sum/#/description

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