您的位置:首页 > 其它

LeetCode - 3Sum Closest

2014-02-25 21:16 302 查看
3Sum Closest

2014.2.25 19:02

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).


Solution:

  This problem is a variation from 3Sum. In that problem, an O(n^2) algorithm was mentioned.

  At first I tried to sort the array and do binary searches, but got an TLE. Then I knew it would still be O(n^2) in time complexity.

  There has to be a minor adjustment for the code of "3Sum". When performing the linear scan from both ends, we not only look for exact match, but also record every sum that is closer to the target. At the end of the search, there will either be a closest sum to the target, or the target value itself.

  Time complexity is O(n^2), space complextiy is O(1).

  The array is not sorted, so extra O(n * log(n)) time is needed for sorting.

Accepted code:

// 2TLE, 1AC, O(n^2) solution, linear scan is faster than binary search.
#include <algorithm>
using namespace std;

class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
int n = (int)num.size();
if (n < 3) {
return 0;
}

int i, j, k;
int res;
int sum;

// sort the array for linear scan
sort(num.begin(), num.end());
// intialize with whatever result here
res = num[0] + num[1] + num[2];
for (i = 0; i < n; ++i) {
j = i + 1;
k = n - 1;
while (j < k) {
sum = num[i] + num[j] + num[k];
if (sum < target) {
++j;
if (myabs(sum - target) < myabs(res - target)) {
res = sum;
}
} else if (sum > target) {
--k;
if (myabs(sum - target) < myabs(res - target)) {
res = sum;
}
} else {
return target;
}
}
}

return res;
}
private:
int myabs(const int n) {
return (n >= 0 ? n : -n);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: