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).和#15的计算3Sum很像,都是找出三个数的sum和一个target的关系
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ rlist=[] nlist=[] nums.sort() for i in range(len(nums)): bindex=i+1 cindex=len(nums)-1 while bindex<cindex: s=nums[i]+nums[bindex]+nums[cindex] comp=abs(s-target) nlist.append(s) rlist.append(comp) if s<target: bindex+=1 elif s> target: cindex-=1 else: return s loc=rlist.index(min(rlist)) return nlist[loc]