LC 1. Two Sum
题目介绍
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
参考答案
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 unordered_map<int,int> hp; 5 int n = nums.size(); 6 vector<int> res; 7 8 for(int i=0;i<n;i++){ 9 10 int rest = target - nums[i]; 11 if(hp.find(rest) != hp.end()){ 12 res.push_back(hp[rest]); 13 res.push_back(i); 14 return res; 15 } 16 hp[nums[i]] = i; // map[key] = value -> map[num] = index; 17 } 18 return res; 19 } 20 };
补充说明
循环分成三部分:
1. 剩下的 = 目标 - 现在的
2. 检查剩下的是否在map里,在的话,就说明是数组里面的数字,可以返回index了。
3. 将该数字存入map中
有一些要特别注意的是:
map[ key ] = value -> map[num] = index ,以数字为key, 以存入的内容为index。所以,搜索的时候,以key(即数字)为依据,而 index 为我们要的结果。