Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Solution: Using Hashmap in C++
The core idea is to see where there is the value 「Target-nums[i]」in the hashmap.
For example : Now the index is in "0" and nums[0] is 2, if there is a solution pair with nums[0]
in the future, the other value should be Target-nums[0] =7. So we will search the Target-nums[i]
value before we insert new elements to the hashmap.
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- vector<int> res;
- unordered_map<int,int> hashmap;
- for(int i=0;i<nums.size();i++){
- if(hashmap.find(target-nums[i])!=hashmap.end()){
- res.push_back(hashmap[target-nums[i]]);
- res.push_back(i);
- return res;
- }
- hashmap[nums[i]]=i;
- }
- res.push_back(-1);
- res.push_back(-1);
- return res;
- }
- };
0 意見:
張貼留言