zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    12.12
    12.11
    1208
    1206
    2018-12-23丛晓强作业
    2018-12-17面向对象总结
    2018-12-17-丛晓强作业
    2018-12-13丛晓强作业
    2018-12-12丛晓强作业
    2018-12-11丛晓强作业
  • 原文地址:https://www.cnblogs.com/grooovvve/p/12360338.html
Copyright © 2011-2022 走看看