Skip to content

Instantly share code, notes, and snippets.

@codinfox
Created January 21, 2015 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codinfox/217fea29e5e7c769c976 to your computer and use it in GitHub Desktop.
Save codinfox/217fea29e5e7c769c976 to your computer and use it in GitHub Desktop.
class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
sort(num.begin(), num.end());
int result = 0, difference = INT_MAX;
for (size_t i = 0; i < num.size() - 2; i++) {
size_t begin = i + 1, end = num.size() - 1;
while (begin < end) {
int tmp_res = num[i] + num[begin] + num[end];
int tmp_diff = tmp_res - target;
if (abs(tmp_diff) < difference) {
result = tmp_res;
difference = abs(tmp_diff);
}
if (tmp_diff < 0) begin++;
else if (tmp_diff > 0) end--;
else return tmp_res; // tmp_diff == 0
}
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment