【c++刷题笔记-哈希表】day06: 242.有效的字母异位词 , 349. 两个数组的交集 , 202. 快乐数 , 1. 两数之和

242. 有效的字母异位词 - 力扣(LeetCode)

思路:统计出每个字符串的长度,然后进行比较

重点:题目限制只有小写字符,所以可以用长度为26的数组来接受字符的个数

class Solution {
public:
    bool isAnagram(string s, string t) {
        int sum[26],sum2[26];
        for(char c:s){
            sum[c-'a']++;
        }
        for(char c:t){
            sum2[c-'a']++;
        }
        for(int i=0;i<26;i++){
            if(sum[i]!=sum2[i]){
                return false;
            }
        }
        return true;
    }
};

思路:用哈希表先统计出第一个数组中的不重复的元素,再遍历第二个数组与哈希表中元素比较

重点:unordered_map是无序的,以键值对的形式存储

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int>hash;
        vector<int>ans;
        for(int a:nums1){
            hash[a]=1;
        }
        for(int a:nums2){
            hash[a]--;//当没有这个元素的时候hash[a]小于0
            if(hash[a]==0){//只有hash[a]==0时元素才表明有交集
                ans.push_back(a);
            }
        }
        return ans;
    }
};

202. 快乐数 - 力扣(LeetCode)

思路:当这个数拆解后,又在某一次中与拆解中的某个数相同时,表明这个数是循环的,所以就不是快乐数

重点:把每次拆解后的数加入哈希表,当出现相同的数的时候跳出循环

class Solution {
public:
    int fun(int n){
        int s=0;
        while(n){
            int a=n%10;
            n/=10;
            s+=a*a;
        }
        return s;
    }
    bool isHappy(int n) {
        unordered_set<int>hash;
        while(1){
            int t=fun(n);
            if(t==1){
                return true;
            }
            if(hash.find(t)!=hash.end()){
                return false;
            }else{
                hash.insert(t);
            }
            n=t;//把下一次循环的值赋值给n
        }
    }
};

1. 两数之和 - 力扣(LeetCode)---------梦开始的地方

思路:将当前需要配对的值存入哈希表中,寻找哈希表中是否有能与当前配对的值,找到后返回对应的下标

重点:使用迭代器iterator访问哈希表会unordered_map有first,second两个指针,前者代表键,后者代表值

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

总结

初学哈希表,哈希表多用在去重,找对应的数。unoreder_map是以键值对的形式存储,unordered_set是一个集合只能存放键

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值