两数之和

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;
        
        
    }
};

 

转载于:https://www.cnblogs.com/Bipolard/p/9994438.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值