Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created October 28, 2017 02:12
Show Gist options
  • Save dgodfrey206/ad2805f5af87dfd0197d94198a8ba2f3 to your computer and use it in GitHub Desktop.
Save dgodfrey206/ad2805f5af87dfd0197d94198a8ba2f3 to your computer and use it in GitHub Desktop.
Returns three numbers from an array that add up to 0
#include<iostream>
#include<vector>
#include<unordered_set>
#include<unordered_map>
using namespace std;
class Solution {
public:
vector<int> threeSum(vector<int>& nums) {
unordered_map<int, int> ht;
for (int i = 0; i < nums.size(); i++) {
if (ht.find(-nums[i]) != ht.end())
return {nums[i], nums[ht[-nums[i]]], -nums[i] - nums[ht[-nums[i]]]};
for (int j = i + 1; j < nums.size(); j++)
ht[nums[i] + nums[j]] = j;
}
return {};
}
};
int main(){
vector<int>v={-1, 0, 1, 2, -1, -4};
auto vv=Solution().threeSum(v);
for(int i:vv)
cout<<i<<" ";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment