Problem:
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.
Solution:
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i, j, k, sum, diff, clos1, clos2, storedMinDiff, storedMaxDiff;
vector<vector<int> > solution;
sort(num.begin(), num.end());
int length = num.size();
storedMinDiff = target - num[length - 1] - num[length - 2] - num[length - 3];
storedMaxDiff = target - num[0] - num[1] - num[2];
for (i = 0; i < num.size(); i++) {
j = i+1;
k = num.size() - 1;
while (j < k) {
sum = num[i] + num[j] + num[k];
diff = target - sum;
if (diff == 0) {
return sum;
} else if (diff < 0) {
k--;
if (diff != max(storedMinDiff, diff))
continue;
storedMinDiff = diff;
// Closest sum in negatives.
clos1 = sum;
} else if (diff > 0) {
j++;
if (diff != min(storedMaxDiff, diff))
continue;
storedMaxDiff = diff;
// Closest sum in positives.
clos2 = sum;
}
}
}
if (abs(target - clos1) < abs(target - clos2))
return clos1;
else
return clos2;
}
};
No comments:
Post a Comment