7.11 学习记录

目录

242.有效的字母异位词

349. 两个数组的交集

202. 快乐数 

1. 两数之和

454.四数相加II

383. 赎金信


代码随想录 (programmercarl.com)icon-default.png?t=N658https://www.programmercarl.com/%E5%93%88%E5%B8%8C%E8%A1%A8%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html#%E5%B8%B8%E8%A7%81%E7%9A%84%E4%B8%89%E7%A7%8D%E5%93%88%E5%B8%8C%E7%BB%93%E6%9E%84 

242.有效的字母异位词

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

class Solution {
public:
    bool isAnagram(string s, string t) {
        int tmp[26]={0};
        for(auto str:s)
        {
            tmp[str-'a']++;
        }
        for (auto str:t)
        {
            tmp[str-'a']--;
            if (tmp[str-'a']<0)return false;
        }
        for (auto ii:tmp)
        {
            if (ii!=0)return false;
        }
        return true;
    }
};

349. 两个数组的交集

349. 两个数组的交集 - 力扣(LeetCode)

class Solution {
public:
    vector intersection(vector& nums1, vector& nums2) {
        unordered_set ans;
        unordered_set tmp(nums1.begin(),nums1.end());
        for(auto num:nums2){
            if (tmp.find(num)!=tmp.end()){
                ans.insert(num);
            }
        }
        return vector(ans.begin(),ans.end());
    }
};

202. 快乐数 

202. 快乐数 - 力扣(LeetCode)

class Solution {
public:
    int getHappy(int n){
        int newnum = 0;
        int tmp = 0;
        while (n!=0){
            tmp = n%10;
            newnum+=tmp*tmp;
            n /=10;
        }
        return newnum;
    }
    bool isHappy(int n) {
        unordered_set dic;
        while(n!=1){
            if(dic.find(n)!=dic.end())return false;
            else dic.insert(n);
            n = getHappy(n);
        }
        return true;
    }
};

1. 两数之和

1. 两数之和 - 力扣(LeetCode)

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        std::unordered_mapmap;
        for(int ii=0;iisecond,ii};
            }
            else{
                map.insert(pair(nums[ii],ii));
            }
        }
        return {};
    }
};

454.四数相加II

454. 四数相加 II - 力扣(LeetCode)

class Solution {
public:
    int fourSumCount(vector& nums1, vector& nums2, vector& nums3, vector& nums4) {
        unordered_map umap;
        for (int a:nums1){
            for (int b:nums2){
                umap[a+b]++;
            }
        }
        int ans = 0;
        for(int c:nums3){
            for(int d:nums4){
                if (umap.find(-c-d)!=umap.end()){
                    ans+=umap[-c-d];
                }
            }
        }
        return ans;
    }
};

383. 赎金信

383. 赎金信 - 力扣(LeetCode)

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int tmp[26] = {0};
        if (ransomNote.size()>magazine.size())return false;
        for(auto str:magazine){
            tmp[str-'a']++;
        }
        for(auto str:ransomNote){
            if(--tmp[str-'a']<0)return false;
        }
        return true;
    }
};

你可能感兴趣的:(学习,leetcode,算法,c++,set,map,哈希表)