Created
January 21, 2015 06:07
-
-
Save codinfox/217fea29e5e7c769c976 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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