[牛客网-Leetcode] #哈希 较难 two-sum

两数之和 two-sum

题目描述

给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
假设给出的数组中只存在唯一解
例如:
给出的数组为 {2, 7, 11, 15},目标值为9
输出 ndex1=1, index2=2

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

示例

输入

[3,2,4],6

输出

[2,3]

解题思路

  • hash表,用unordered_map记录“元素值->数组下标”的映射
#include <unordered_map>
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> res;
        unordered_map<int, int> mp;
        int size = numbers.size();
        //初始化hash表
        for(int i = 0; i < size; i ++) {
            mp[numbers[i]] = i;
        }
        for(int i = 0; i < size; i ++) {
            int temp = target - numbers[i];
            //如果在mp中找到互补的元素,则添加进结果
            //同时要确保互补的数不是它本身
            if(mp.find(temp) != mp.end() && mp[temp] > i) {
                res.push_back(i + 1);  //由于下标是从1开始的,所以要加一
                res.push_back(mp[temp] + 1);
                break;
            } else {
                //如果在mp中没找到互补的元素,则直接跳过
                continue;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值