3Sum Closest

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).

分析:

此题和3Sum思路类似,只是每次都要记录目前最优结果,代码如下:

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        i = 0
        res = nums[0]+nums[1]+nums[2]
        while i < len(nums):
            l = i+1
            r = len(nums)-1
            while l < r:
                if l < r and nums[i]+nums[l]+nums[r] == target:
                    return target
                while l < r and nums[i]+nums[l]+nums[r] < target:
                    if abs(nums[i]+nums[l]+nums[r]-target) < abs(res-target):
                        res = nums[i]+nums[l]+nums[r]
                    while l < r and nums[l+1] == nums[l]:
                        l += 1
                    l += 1
                while l < r and nums[i]+nums[l]+nums[r] > target:
                    if abs(nums[i]+nums[l]+nums[r]-target) < abs(res-target):
                        res = nums[i]+nums[l]+nums[r]
                    while l < r and nums[r-1] == nums[r]:
                        r -= 1
                    r -= 1
            i += 1
        return res
原文地址:https://www.cnblogs.com/Peyton-Li/p/8094622.html