Created
September 2, 2018 02:42
-
-
Save zhangxiaomu01/03c50ce167c48313a2d7965e1a1315a0 to your computer and use it in GitHub Desktop.
Implementation of two sum problem (hash table)
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: | |
vector<int> twoSum(vector<int>& nums, int target) { | |
vector<int> Result; | |
unordered_map<int, int> hash; | |
for(int i =0 ;i< nums.size(); i++) | |
{ | |
int numOfComplement = target - nums[i]; | |
if(hash.find(numOfComplement) != hash.end()) | |
{ | |
int temp = hash[numOfComplement]; | |
Result.push_back(temp); | |
Result.push_back(i); | |
return Result; | |
} | |
else | |
hash[nums[i]] = i; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment