59.3Sum Closest
1.Description(Medium)
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.
Notice
You may assume that each input would have exactly one solution.
Example
For example, given arrayS=[-1 2 1 -4]
, and target =1
. The sum that is closest to the target is2
.(-1 + 2 + 1 = 2).
O(n^2) time, O(1) extra space
2.Code
3sum问题的变种。一样的遍历每个数,对剩余数组进行双指针扫描。区别仅仅在于当:
sum = A[left] + A[right]
(1) sum = target时直接返回
(2) sum != target时,在相应移动left/right指针之前,先计算abs(sum-target)的值,并更新结果。
Last updated