leetcode01 twosum c++

题目

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

**

思路

**
建立哈希表,在遍历数组建立哈希表的时候就可以进行查找了,若找到goal,证明数据已经存在,只需要在返回查找到的值在数组中的下标值和当前遍历数组的位置即可

**

解答

**

vector<int> twoSum(vector<int>& nums, int target) {
  if(nums.size()<2) return vector<int>{};
    map<int,int> nums_map;
    vector<int> res_vec;
    for(int i = 0; i<nums.size(); i++){
        int goal = target - nums[i];
        if(nums_map.end()!= nums_map.find(goal)){
            res_vec.emplace_back(nums_map[goal]);
            res_vec.emplace_back(i);
            break;
        }else{
            nums_map[nums[i]] = i;
        }
    }
    return res_vec;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值