例如,给定的整数 S = {-10 20 10 -40}, 目标值 = 10. 最接近目标值的和为 2. (-10 + 20 + 10 = 20).
import sys class Solution: def threeSumClosest(self , num , target ): # write code here n,temp,minus,res=len(num),0,sys.maxsize,0 for i in range(n): for j in range(n): for k in range(n): if i!=j and j!=k and i!=k: if abs(target-num[i]-num[j]-num[k])<=minus: minus=abs(target-num[i]-num[j]-num[k]) res=num[i]+num[j]+num[k] return res
# @param num int整型一维数组 # @param target int整型 # @return int整型 # class Solution: def threeSumClosest(self , num , target ): # write code here if len(num) == 3: return num[0]+num[1]+num[2] num.sort() res = num[0]+num[1]+num[2] for i in range(len(num)): start = i+1 end = len(num) - 1 while start < end: cur_min = num[i] + num[start] + num[end] if cur_min == target: return target if abs(cur_min - target) < abs(res - target): res = cur_min if cur_min < target: start += 1 else: end -= 1 return res
# # # @param num int整型一维数组 # @param target int整型 # @return int整型 # class Solution: def threeSumClosest(self , num , target ): # write code here if len(num)>=3: num.sort() getsum=num[0]+num[1]+num[2] else: return 0 for i in range(len(num)-2): j = i+1 k = len(num)-1 while(j<k): diff = (num[i]+num[j]+num[k]-target) j=j+1 k=k-1 if abs(diff) > abs(num[i]+num[j]+num[k]-target): result = num[i]+num[j]+num[k] else: result = diff+target diff = min(abs(num[i]+num[j]+num[k]-target),abs(diff)) return result