C++ 哈希表代码练习

代码1,对应力扣消失的数字,代码见下:

class Solution {
public:
    int missingNumber(vector<int>& nums) {
        unordered_map<int, int> hash;
        for(int i=0; i<nums.size(); ++i){
            hash[nums[i]] = 1;
        }
        for(int i=0; ;++i){
            if(hash.find(i) == hash.end()){
                return i;
            }
        }
    }
};

代码2,对应力扣,缺失的第一个正数,代码见下

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        unordered_map<int, bool> hash;
        for(int i=0; i<nums.size(); ++i){
            hash[nums[i]] = true;
        }
        for(int i=1; ; ++i){
            if(hash.find(i) == hash.end()){
                return i;
            }
        }
        return -1;
    }
};

代码三,对应力扣寻找文件副本,代码见下:

class Solution {
public:
    int findRepeatDocument(vector<int>& documents) {
        unordered_map<int, bool> hash;
        for(int i=0; i<documents.size(); ++i){
            if(hash.find(documents[i]) != hash.end()){
                return documents[i];
            }
            hash[documents[i]] = true;
        }
        return 0;
    }
};

代码四,对应力扣,两数之和,代码见下:

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

        }
        return {};
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值