moonlightshadow123
6/21/2017 - 9:24 AM

15. 3Sum

  1. 3Sum
class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums = sorted(nums)
        self.closest = float('inf')
        firstIndex = 0
        while firstIndex <= len(nums) - 3:
            self.twoSum(nums, firstIndex, target)
            firstIndex += 1
            while nums[firstIndex] == nums[firstIndex - 1] and firstIndex <= len(nums) - 3:
                firstIndex += 1
        return self.closest
        
    def twoSum(self, nums, firstIndex, target):
        beginIndex = firstIndex + 1
        endIndex = len(nums) - 1
        while beginIndex < endIndex:
            curSum = nums[firstIndex] + nums[beginIndex] + nums[endIndex]
            self.closest = curSum if abs(curSum-target) < abs(self.closest-target) else self.closest 
            if curSum < target:
                beginIndex += 1
                while nums[beginIndex] == nums[beginIndex - 1] and beginIndex < endIndex:
                    beginIndex += 1
            elif curSum > target:
                endIndex -= 1
                while nums[endIndex] == nums[endIndex + 1] and beginIndex < endIndex:
                    endIndex -= 1
            else:
                break

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

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:

[
  [-1, 0, 1],
  [-1, -1, 2]
]