Leetcode1. 两数之和 -hot100-代码随想录

题目:


代码(首刷看解析 2024年1月15日):

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int another = 0;
        unordered_map<int,int> hash;
        for(int i = 0; i < nums.size(); ++i) {
            another = target - nums[i];
            if(hash.find(another) != hash.end()) return {i,hash[another]};
            else hash.emplace(nums[i],i);
        }
        return {0,0};
    }
};

        一开始做的时候把所有的数先存进hash表里再去找,结果这种情况无法满足重复key值,用multimap又无法检索键对应的值,最后看了代码随想录里的思路发现在遍历过程中插入即可。


代码(二刷自解 2024年3月2日 7min)

        开始hot一百刷题之旅

class Solution {
public:
    // 哈希
    vector<int> twoSum(vector<int>& nums, int target) {
            // 条件判断
            if (nums.size() < 2) return vector<int>{0, 1};
            // hash存储 value:index
            unordered_map<int, int> hash;
            // 遍历取哈希
            for (int i = 0; i < nums.size(); ++i) {
                if (hash.find(target - nums[i]) != hash.end()) {
                    return vector<int>{i, hash[target - nums[i]]};
                } else {
                    hash.insert(pair<int,int>(nums[i], i));
                }
            }
            return vector<int>{0, 1};
    }
};

代码(三刷自解,2024年4月23日 bugfree)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // hash存下标,每次遍历的时候往里面存
        unordered_map<int, int> value_to_index;
        for (int i = 0; i < nums.size(); i++) {
            // 先检测是否存在
            if (value_to_index.find(target - nums[i]) != value_to_index.end()) {
                return {value_to_index[target - nums[i]], i};
            } else {
                value_to_index[nums[i]] = i;
            }
        }
        return {-1,-1};
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值