Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ustbgaofan/519717ea228ad8c3ca84eb86633a2542 to your computer and use it in GitHub Desktop.
Save ustbgaofan/519717ea228ad8c3ca84eb86633a2542 to your computer and use it in GitHub Desktop.
two sum: Given nums = [2,7,11,15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]
#include <unordered_map>
class Solution {
public:
vector<int> twoSum(vector<int> &number, int targe)
{
//Key is the number and value is its index in the vector.
unordered_map<int, int > hash;
vector<int> result;
for(i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if(hash.find(numberToFind) != hash.end()) {
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
//number was not found .Put it in the map
hash[number[i]] = i;
} //end for loop
return result;
} //end func
};//end class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment