【LeetCode】16. 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).

题意:给出一个数组和一个目标值,在数组中找出和目标值最接近的三个值的和

思路:和LeetCode:15. 3Sum一样,先找出一个值,然后用其余的两个指针不断的找出距离目标插值最小的两个值,每次找出时候刷新三个数的和

 1 class Solution(object):
 2     def threeSumClosest(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         nums.sort()
 9         l = len(nums)
10         i = 0
11         min=9999999999
12         while i<l-2:
13             begin=i+1;end=l-1
14             tmp=nums[begin]+nums[end]
15             cool = target-nums[i]
16             while begin<end:
17                 if abs(tmp-cool)<min:
18                     min=abs(tmp-cool)
19                     sum=nums[begin]+nums[end]+nums[i]
20                 if cool<tmp:
21                     end-=1
22                 elif cool>tmp:
23                     begin+=1
24                 else:
25                     return target
26                 tmp=nums[begin]+nums[end]
27             i+=1
28         return sum

ps:我还能说什么,晚上不适合做题。。。智商不足

原文地址:https://www.cnblogs.com/fcyworld/p/6213227.html