力扣算法篇:哈希集合

使用哈希集查重

/*
 * Template for using hash set to find duplicates.
 */
bool findDuplicates(vector<Type>& keys) {
    // Replace Type with actual type of your key
    unordered_set<Type> hashset;
    //C++11 for循环新写法
    for (Type key : keys) {
        if (hashset.count(key) > 0) {
            return true;
        }
        hashset.insert(key);
    }
    return false;
}

存在重复元素

题目:
在这里插入图片描述
题解:

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        //使用哈希集判断
        unordered_set<int> hashset;
        for(int num:nums){
            if(hashset.count(num)>0){
                //该元素已存在
                return true;
            }
            hashset.insert(num);
        }
        return false;
    }
};

只出现一次的数字

在这里插入图片描述
题解:

class Solution {
public:
    int singleNumber(vector<int>& nums) {
         //使用哈希集判断
        unordered_set<int> hashset;
        for(int num:nums){
            if(hashset.count(num)>0){
                //该元素已存在
                //删除
                hashset.erase(num);
            }else{
                //不存在 加入
                hashset.insert(num);
            }
        }
        //哈希集合中只有出现一次的元素 返回即可
        return *(hashset.begin());
    }
};

两个数组的交集

在这里插入图片描述
题解:

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        //返回vector
        vector<int> result;
        //哈希集
        unordered_set<int> hashset;
        //遍历一个vector将值加入哈希集中
        for(int num:nums1){
            //没有必要用if语句判断 insert之前它会判断是否存在
            hashset.insert(num);
        }
        
        //遍历另一个vector
        for(int num:nums2){
            if(hashset.count(num)>0){
                //存在 交集元素之一
                result.push_back(num);
                //在哈希表中删除元素 这样重复元素就不会被重复加入
                hashset.erase(num);
            }
        }
        return result;
    }
};

快乐数

在这里插入图片描述
题解:

class Solution {
public:
    bool isHappy(int n) {
        //哈希集 
        unordered_set<int> hashset;
        int m = n;
        while(m!=1){
            hashset.insert(m);
            int sum = 0;
            while(m!=0){
                sum += pow(m%10,2);
                m = m/10;
            }
            //将和又赋值给m
            m = sum;
            //如果得到的数跟之前的重复 就一定不是快乐数
            if(hashset.find(m)!=hashset.end()){
                //找到了 重复
                return false;
            }
        }

        //除了循环说明m(sum)为1
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值