3 Sum 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.
http://www.lintcode.com/en/problem/3-sum-closest/
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).
You may assume that each input would have exactly one solution.
O(n^2) time, O(1) extra space
Discussion
找最接近的那一组,二分行不通了,即使是排序以后也不行,因为可能错过最接近的那一组。先排序,再用两个首尾指针夹逼之。。
Solution
class Solution {
public:
/**
* @param numbers: Give an array numbers of n integer
* @param target: An integer
* @return: return the sum of the three integers, the sum closest target.
*/
int threeSumClosest(vector<int> nums, int target) {
// write your code here
sort(nums.begin(), nums.end());
vector<int>::iterator it;
int result =0;
int minGap = INT_MAX;
for(it=nums.begin(); it<prev(nums.end(),2); it++) {
auto start = next(it);
auto end = prev(nums.end());
while(start < end) {
int sum = *it + *start + *end;
int gap = abs(sum-target);
if(gap < minGap) {
minGap = gap;
result = sum;
}
if(sum < target)
start++;
else
end--;
}
}
return result;
}
};