代码随想录 Day 6

242.有效的字母异位词

哈希法核心就是把数据存起来,所以这个题虽然是在用 数组但是还是哈希法

class Solution {
public:
    bool isAnagram(string s, string t) {
        //int stor[26]; 这行没初始化会报错
        int stor[26] = {0};
        for (int i = 0; i < s.size(); i++){
            int j = s[i] - 'a';
            stor[j]++;
        }

        for(int i = 0; i < t.size(); i++){
            int j = t[i] - 'a';
            stor[j]--;
        }

        for(int i = 0; i < 26; i++){
            if(stor[i] != 0){
                return false;
            }
         }
         return true;
    }
};

349. 两个数组的交集

下面解释了上面那个题为什么不直接用set来做

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> result_set;
        unordered_set<int> nums_set(nums1.begin(),nums1.end()); //这句话定义了一个nums_set的set, 然后把nums1的数据传进去
        for (int num : nums2){
             if (nums_set.find(num) != nums_set.end()) {
                result_set.insert(num);
        }
    }
    return vector<int>(result_set.begin(), result_set.end());
    }
};

202. Happy Number

class Solution {
public:
//int get_sum(){ 这句自己写的函数没写参数,一开始打算在函数中定义函数但是C++不允许
int get_sum(int n){
           int sum = 0;
           while (n) {  //这句自己没写出来,自己考虑的时候想写个for循环一直到这个数结束;
                sum += (n % 10) * (n % 10) ;
                //sum = sum/10;这句写错了
                n = n / 10;
           }  
           return sum;   
       } 

    bool isHappy(int n) {
        unordered_set<int> set;

        while(1) {
            int result = get_sum(n);
            if (result == 1) {
                return true;
            }
            if(set.find(result) != set.end()) {
                return false;
            } else {
                set.insert(result);
            }
            n= result;
       }
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值