Skip to content

Instantly share code, notes, and snippets.

@weidagang
Last active December 25, 2015 00:19
Show Gist options
  • Select an option

  • Save weidagang/6887359 to your computer and use it in GitHub Desktop.

Select an option

Save weidagang/6887359 to your computer and use it in GitHub Desktop.
/*
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
*/
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
unordered_map<int, int> v2i;
for (int i = 0; i < numbers.size(); ++i) {
unordered_map<int, int>::iterator it = v2i.find(target - numbers[i]);
if (v2i.end() != it) {
result.push_back(it->second + 1);
result.push_back(i + 1);
break;
}
else {
v2i[numbers[i]] = i;
}
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment