[算法题] 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).

题目思路

题目难度:medium

本题在3sum的基础上稍稍变了一下。在3sum中,返回的条件是target等于三个数的和,而在这里返回的条件是三个数的和到target的距离最近。因此本题和3sum的区别在于:需要调整一下返回值的取法。而通过双指针法的思想不变。

Python代码

class Solution(object):
    def threeSumClosest(self, nums,target):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums=sorted(nums)
        _len=len(nums)
        the_min=999999
        res=0
        for i in xrange(_len-2):
            tar=nums[i]
            left=i+1
            right=_len-1
            while left<right:
                _sum=nums[left]+nums[right]
                if abs(_sum+tar-target)<the_min:
                    res=nums[i]+nums[left]+nums[right]
                    the_min=abs(_sum+tar-target)
                if _sum+tar-target<0:
                    left+=1
                else:
                    right-=1
        return res 
原文地址:https://www.cnblogs.com/chengyuanqi/p/7130911.html