LeetCode | 1) Two sum

本文探讨了在给定整数数组中寻找两个数相加等于特定目标值的问题,并提供了三种解决方案。第一种为简单的双层循环遍历,第二种利用哈希表减少查找时间,第三种进一步优化哈希表使用,实现高效查找。

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

题目

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.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    };
}

思路

  • 方案 1:两次循环遍历整个数组,检测nums[i] + nums[j] == target,时间复杂度 O(N2)

  • 方案 2:首先利用map<int, size_t>将数据和对应的下标存储起来;然后一次遍历数组,在hash map中查找tartget - nums[i],时间复杂度是 O(n)O(1)=O(N) . 该方法需要两次hash,一次是建立hash表,另一次是查找hash表,存在有可能找到的数和num[i]一样这个问题

  • 方案 3:只用一遍hash表。首先查找hash表中是否存在nums[i],不存在则将target - nums[i]存储在hash表中。


代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        vector<int> vec;
        unordered_multimap<int, size_t> numMap;
        //元素之间没有序关系,宜用unordered_map; nums数组中有多个同样的数,宜用multimap
        //综合考虑,使用unordered_multimap

        for (size_t it = 0; it != nums.size(); ++it)
        {
            auto iter = numMap.find(nums[it]);//先对numMap进行查找
            if (iter == numMap.end())
            {
                numMap.insert({target - nums[it], it});//没有找到则插入数据和下标
            }
            else
            {
                return vector<int>{iter->second, it};
                //找到,直接返回numMap的迭代器iter指向的下标(iter->second)和当前nums的下标it。
            }
        }
        return vec;
    }
};

运行时间:19ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值