1. 程式人生 > >LeetCode[Array]----3Sum Closest

LeetCode[Array]----3Sum Closest

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