Skip to content

Instantly share code, notes, and snippets.

@kirainmoe kirainmoe/two_sum.cpp
Last active Dec 18, 2016

Embed
What would you like to do?
Two sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
map<int, int> numMap;
int size = nums.size();
if (size < 2) {
return res;
}
for (int i = 0; i < size; i ++)
{
numMap.insert(pair<int, int>(nums[i], i));
}
map<int, int>::iterator iter;
for (int i = 0; i < size; i ++)
{
if ((iter = numMap.find(target - nums[i])) != numMap.end()) {
if (i == iter->second) // repeat
continue;
cout << nums[i] << nums[iter->second];
res.push_back(i);
res.push_back(iter->second);
return res;
}
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.