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).
分析:
此题为3Sum一题的升级版。题意为在给定数组中找到三个元素a,b,c,使得a + b + c的和最接近给定的target,返回a + b + c。
题目限定了这个三个元素一定能够找到并且唯一。
这里我们借鉴3Sum一题的思路,还是对数组nums进行排序,然后使用双指针进行遍历。
但是与上一题不一样的是,我们这里找到的三个元素和一般来说不会等于target,如果三元素和nsum大于target,那么右指针向左移动,降低nsum值;如果nsum值小于target,那么左指针向右移动,增加nsum值;当然,如果nsum等于target,那么直接返回nsum就好了。通过两个指针的移动,可以使得nsum不断的逼近target。
在指针的移动过程中,我们需要实时记录当前的nsum和target的差值,从中选择差值绝对值最小的nsum为最接近target的和的结果。
相应的代码为:
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ dmin = float('inf') nums.sort() for i in range(len(nums) - 2): left = i + 1 right = len(nums) - 1 while left < right: nsum = nums[left] + nums[right] + nums[i] if abs(nsum - target) < abs(dmin): dmin = nsum - target minsum = nsum if nsum > target: right -= 1 if nsum < target: left += 1 if nsum == target: return nsum return minsum
时间: 2024-10-03 05:45:28