--

leetcode 016: 3 sum closest



https://leetcode.com/problems/3sum-closest/



problem:
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

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



start code (c++)
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        


solution:

我的思路:



class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        minAbsDiff = -1
        ans = -1
        for i, v in enumerate(nums):
            if i > len(nums) -3:
                break
            beg = i + 1
            end = len(nums) -1
            while end > beg:
                sum3 = v + nums[beg] + nums[end]
                diff = sum3 - target
                if diff == 0:
                    return sum3
                if minAbsDiff == -1:
                    minAbsDiff = abs(diff)
                    ans = sum3
                else:
                    if abs(diff) < minAbsDiff:
                        minAbsDiff = abs(diff)
                        ans = sum3
                if diff > 0:
                    end -= 1
                else:
                    beg += 1
        return ans