Leetcode#1 Two Sum
Published:
Link:
https://leetcode.com/problems/two-sum/description/
Idea:
HashTable: value -> index
Solution:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> target_index;
for(int i=0; i<nums.size(); i++) {
target_index[nums[i]] = i;
}
vector<int> res;
int first, second;
for (int i=0; i<nums.size(); i++) {
if (target_index.count(target-nums[i]) > 0 && target_index[target-nums[i]] != i){
first = i;
second = target_index[target-nums[i]];
break;
}
}
res.push_back(first);
res.push_back(second);
return res;
}
};