moonlightshadow123
6/21/2017 - 9:30 AM

16. 3Sum Closest

  1. 3Sum Closest
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, firstIndex+1, target)
            firstIndex += 1
            while nums[firstIndex] == nums[firstIndex - 1] and firstIndex <= len(nums) - 3:
                firstIndex += 1
        return self.closest
        
    def twoSum(self, nums, firstIndex, beginIndex, target):
        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-closest/#/description

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).