LeetCode OJ 之 Two Sum(两个数的和)

本文介绍了一种高效的算法来解决两数之和的问题。给定一个整型数组及一个目标值,通过使用哈希表实现快速查找,找到数组中两个数相加等于目标值的下标。该算法的时间复杂度为O(n),显著提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

函数返回两个数的下标(注意返回的这个下标是在数组中的下标+1),其中下标1必须小于下标2.注意返回的答案不能是0.

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

你可以假定每个输入都有一个正确的结果。

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2(返回的下标是在数组中的下标+1)

注意:可以采用暴力法搜索,但是复杂度为O(n^2),答案通不过,会超时。

本题可以采用哈希表,直接寻址法,map的键为数组的数,值为对应的下标,复杂度为O(n).

代码:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) 
    {
        unordered_map<int, int> mapping;//定义非排序map
        vector<int> ivec;//返回结果
        for(int i=0;i < numbers.size();i++)
        {
            mapping[numbers[i]]=i;//把数组的数和下标存储到man中的键值里
        }
        for(int i = 0;i < numbers.size() ;i++)
        {
            int gap=target-numbers[i];//找到差值即找到符合条件的下标
            if(mapping.find(gap) != mapping.end() && mapping[gap] > i)//迭代器没有到最后,gap对应的下标比i大
            {
                ivec.push_back(i + 1);
                ivec.push_back(mapping[gap] + 1);
                break;
            }
        }
        return ivec;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值