LeetCode Medium: 16. 3Sum Closest

一、题目

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

二、思路

同前面的求三个数的和是否为1思路一样,这类基本上就是用两个指针,一个指头,一个指尾,然后根据条件来进行指针的移动。

 三、代码

#coding:utf-8
def threeSumClosest(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: int
    """
    closettarget = 0
    diff = float("inf")
    newnums = sorted(nums)
    for currentpoint in range(len(newnums)-2):
        leftpoint = currentpoint + 1
        rightpoint = len(newnums)-1
        while leftpoint < rightpoint:
            a = sum([newnums[currentpoint],newnums[leftpoint],newnums[rightpoint]])
            tmp = abs(target - a)
            if tmp < diff:
                closettarget = a
                diff = tmp
            if a < target:
                leftpoint+=1
            elif a > target:
                rightpoint-=1
            else:
                print(a)
                return a
    print(closettarget)
    return closettarget

if __name__ == '__main__':
    nums = [0,1,2]
    threeSumClosest(nums,3)