leetcode 242 && 349 && 202 & 383

这些题都挺无聊的 ORZ 

leetcode  242. 有效的字母异位词 easy          

题目描述:

 

解题思路:

hash表统计词频

代码:

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

 leetcode  349. 两个数组的交集 easy     

题目描述:

 

解题思路:

hash set 存就完事了

代码:

//
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {

        unordered_set<int> hash(nums1.begin(), nums1.end());        
        unordered_set<int> res;
        for (int i: nums2)
        {
            if (hash.count(i))
                res.insert(i);
        }

        return vector<int>(res.begin(), res.end());
    }
};

 leetcode 202. 快乐数  easy         

题目描述:

 

解题思路:

模拟这个过程, hashset 用来判断是否当前的数之前出现过就完事了

代码:

//
class Solution {
public:
    bool isHappy(int n) {

        unordered_set<int> hash;
        while (n != 1 && !hash.count(n)){
            hash.insert(n);
            n = get_next(n);
        }

        return n==1;

    }

    int get_next(int n){
        int res = 0;
        while (n){
            res += pow(n%10, 2);
            n /= 10;
        }

        return res;
    }

};

 leetcode 383. 赎金信  easy    

题目描述:

 

解题思路:

无聊

代码:

//
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {

        unordered_map<char,int> hash;
        for (char c: magazine)
            hash[c]++;
        for (char c: ransomNote)
        {
            if (hash.count(c))
            {
                if (hash[c] <= 0)
                    return false;
                hash[c]--;
            }

            else
                return false;
        }
        return true;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值