Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created September 5, 2019 07:22
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 vitkarpov/b5b5cf40f32a9114827f6690833fe684 to your computer and use it in GitHub Desktop.
Save vitkarpov/b5b5cf40f32a9114827f6690833fe684 to your computer and use it in GitHub Desktop.
Binary Search Approach (https://leetcode.com/problems/two-sum)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<pair<int, int>> numsNpos;
for (auto i = 0; i < nums.size(); i++) {
numsNpos.push_back({ nums[i], i });
}
sort(numsNpos.begin(), numsNpos.end());
for (auto i = numsNpos.begin(); i != numsNpos.end(); ++i) {
auto k = target - (*i).first;
pair<int, int> t = {k, 0};
auto j = lower_bound(i + 1, numsNpos.end(), t);
if (j != numsNpos.end() && k == (*j).first) {
return {(*i).second, (*j).second};
}
}
assert(false);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment