zoukankan      html  css  js  c++  java
  • 两数之和

    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].
    

     题意:给定的数组,找到其中两个数,满足和为给定的值,返回这两个数的下标

    思路:利用哈希映射,遍历数组,一边向哈希表中插入数值,下标的键值对,一遍在哈希表里面查找有没有(target-这个数),如果有的话,把两个数的下标添加到数组,返回。

    class Solution {
    public:
        //数组的数值,下标作为键值对保存到map
        //遍历数组的时候,在map 中找target-num,如果能找到就把坐标push进ans,两个下标的顺序无所谓
        //如果没有找到,就插入新的键值对
        vector<int> twoSum(vector<int>& nums, int target) {
            unordered_map<int,int> m;
            vector<int> ans;
            for(int i=0;i<nums.size();i++){
                if(m.count(target-nums[i]) && m[target-nums[i]]!=i){  //这里没有判断和i相等也可以
                    ans.push_back(i);
                    ans.push_back(m[target-nums[i]]); 
                }
                else m[nums[i]]=i;
            }
            return ans;
            
            
        }
    };
  • 相关阅读:
    关于多态
    关于lock锁
    wait()和notify()
    多线程之间的通讯
    多线程的异步请求模式
    合理配置线程池
    自定义线程池
    Curl的毫秒超时的一个”Bug”
    Nginx正确记录post日志的方法
    NGINX的奇淫技巧 —— 5. NGINX实现金盾防火墙的功能(防CC)
  • 原文地址:https://www.cnblogs.com/Bipolard/p/9994438.html
Copyright © 2011-2022 走看看