LeetCode[Array]----3Sum Closest

来源:互联网 发布:宁波行知小学怎么样 编辑:程序博客网 时间:2024/05/01 08:50

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一题的升级版。题意为在给定数组中找到三个元素a,b,c,使得a + b + c的和最接近给定的target,返回a + b + c。

题目限定了这个三个元素一定能够找到并且唯一。

这里我们借鉴3Sum一题的思路,还是对数组nums进行排序,然后使用双指针进行遍历。

但是与上一题不一样的是,我们这里找到的三个元素和一般来说不会等于target,如果三元素和nsum大于target,那么右指针向左移动,降低nsum值;如果nsum值小于target,那么左指针向右移动,增加nsum值;当然,如果nsum等于target,那么直接返回nsum就好了。通过两个指针的移动,可以使得nsum不断的逼近target。

在指针的移动过程中,我们需要实时记录当前的nsum和target的差值,从中选择差值绝对值最小的nsum为最接近target的和的结果。


相应的代码为:

class Solution(object):    def threeSumClosest(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        dmin = float('inf')        nums.sort()        for i in range(len(nums) - 2):            left = i + 1            right = len(nums) - 1            while left < right:                nsum = nums[left] + nums[right] + nums[i]                if abs(nsum - target) < abs(dmin):                    dmin = nsum - target                    minsum = nsum                if nsum > target:                    right -= 1                if nsum < target:                    left += 1                if nsum == target:                    return nsum        return minsum

0 0
原创粉丝点击