您的位置:首页 > 其它

LeetCode 16. 3Sum Closest

2016-04-12 22:44 363 查看
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).


same idea as Three Sum question: three pointers.

If use HashMap, it can be changed into Two Sum question.

#include <vector>
#include <algorithm>
#include <iostream>
#include <climits>
using namespace std;

// Suppose such a triplet must exist.
// inputs may contain duplicates.
int threeSumCloset(vector<int>& nums, int target) {
sort(nums.begin(), nums.end()); // nlgn time complexity.
int i = 0;
int closetSum;
int minDiff = INT_MAX;
while(i < nums.size()) {    // o(n2) time complexity
if(i > 0 && nums[i] == nums[i-1]) {
i++;
continue;
}
int start = i + 1;
int end = nums.size() - 1;
while(start < end) {
if(start - 1 > i && nums[start] == nums[start - 1]) {
start++;
continue;
}
if(end + 1 < nums.size() && nums[end] == nums[end + 1]) {
end--;
continue;
}
int sum = nums[i] + nums[start] + nums[end];
if(abs(sum - target) < minDiff) {  // actually once we found a 0, we can just stop and return.
minDiff = abs(sum - target);
closetSum = sum;
}
if(sum >= target) end--;
else start++;
}
i++;
}
return closetSum;
}

int main(void) {
vector<int> nums{-1, 2, 1, 4};
int res = threeSumCloset(nums, 1);
cout << res << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: