LeetCode1_两数之和

思路:

1、遍历数组-构建map:用一个map存储遍历数组获取<数值,索引>这样的键值对。方便查找想要的某个数值的位置;

2、遍历数组-查询map:再遍历一遍数组,通过查询map确定是否存在两个数之和为目标值;同时注意不能重复利用这个数组中同样的元素;

 

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         map<int,int> record;            //<数值,索引>
 5         vector<int> res;
 6         for(int i = 0; i<nums.size(); i++){
 7             record[nums[i]]=i;
 8         }
 9 
10         for(int i = 0; i<nums.size(); i++){
11             if(record.find(target-nums[i]) != record.end() && record[target-nums[i]]!=i){
12                 res.push_back(i);
13                 res.push_back(record.find(target-nums[i])->second);
14                 return res;
15             }
16         }
17         throw invalid_argument("the input has no solution!");
18     }
19 
20 };

 

posted @ 2020-02-25 10:23  Grooovvve  阅读(137)  评论(0编辑  收藏  举报