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).
AC代码:
class Solution(object): def threeSumClosest(self, nums, target): if len(nums) < 3: return 0 ret_num = nums[0] + nums[1] + nums[2] nums.sort() for i_1st in xrange(len(nums) - 2): # remove duplicates if i_1st > 0 and nums[i_1st] == nums[i_1st - 1]: continue i_2nd, i_3rd = i_1st + 1, len(nums) - 1 while i_2nd < i_3rd: s = nums[i_1st] + nums[i_2nd] + nums[i_3rd] if s == target: return target if s > target: i_3rd -= 1 else: i_2nd += 1 if abs(s - target) < abs(ret_num - target): ret_num = s return ret_num
本题和15. 3Sum的双指针解法基本一模一样,只不过本题求的是最接近目标值的和,思想上是一样的。