Created
October 28, 2017 02:12
-
-
Save dgodfrey206/ad2805f5af87dfd0197d94198a8ba2f3 to your computer and use it in GitHub Desktop.
Returns three numbers from an array that add up to 0
This file contains hidden or 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
#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