1. Two Sum
Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.
You may assume that each input would haveexactlyone solution, and you may not use thesameelement twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Thoughts:
map key-value pair of component of the sum
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map <int, int> map;
vector <int> ans;
for (int i = 0; i< nums.size(); i++){
int res = target - nums[i];
if (map.find(res) != map.end()){
ans.push_back(map[res]);
ans.push_back(i);
return ans;
}
map[nums[i]] = i;
}
return ans;
}
};
Alternatively, I can first sort the vector _nums _and use two pointer (but the time complexity becomes sort dominant O(nlogn))