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.
1 | For example, given array S = {-1 2 1 -4}, and target = 1. |
除了O(N3)的穷举解法外,还可以通过对数组排序,假设第一个数已经确定,第二个数从左边扫,第三个数从右边扫,然后根据当前和与目标值比较的结果调整第二个或第三个数的位置,时间复杂度O(N2)
1 | class Solution { |