4-1/4-3set和map的使用

news/2024/9/28 11:11:38 标签: set, map, lLeetCode, c++

目录

LeetCode349 easy

LeetCode350 easy

LeetCode242 easy

LeetCode202 easy

LeetCode290 easy

LeetCode205 easy

LeetCode451 medium


LeetCode349 easy

方法1:使用set

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> result;  //保存结果,为了去重,所以用set
        unordered_set<int> nums(nums1.begin(),nums1.end()); //将nums1变成set
        for(int num:nums2)  //遍历nums2中的元素
        {
            if(nums.find(num)!=nums.end())
            {
                result.insert(num); //如果找到就放到结果集合中
            }
        }
        return vector<int>(result.begin(),result.end()); //将set变成vector
    }
};

LeetCode350 easy

方法1:使用unordered_map

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int,int> um;
        vector<int> res;
        for(auto temp:nums1)
        {
            um[temp]++;
        }
        for(auto temp:nums2)
        {
            if(um[temp]>0)
            {
                res.push_back(temp);
                um[temp]--;
            }
        }
        return res;
    }
};

方法2:排序+双指针

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        int length1 = nums1.size(), length2 = nums2.size();
        vector<int> intersection;
        int index1 = 0, index2 = 0;
        while (index1 < length1 && index2 < length2) {
            if (nums1[index1] < nums2[index2]) {
                index1++;
            } else if (nums1[index1] > nums2[index2]) {
                index2++;
            } else {
                intersection.push_back(nums1[index1]);
                index1++;
                index2++;
            }
        }
        return intersection;
    }
};

LeetCode242 easy

class Solution {
public:
    bool isAnagram(string s, string t) {
        int s1=s.size();
        int s2=t.size();
        if(s1!=s2)
        {
            return false;
        }
        int res[26]={0};
        for(auto c:s)
        {
            res[c-'a']++;
        }
        for(auto c:t)
        {
            res[c-'a']--;
        }
        for(auto c:res)
        {
            if(c!=0)
                return false;
        }
        return true;

    }
};


LeetCode202 easy

方法1:使用快慢指针

class Solution {
public:
    int bitSquareSum(int n) {   //求n的各位数字的平方和
        int sum = 0;
        while(n > 0)
        {
            int bit = n % 10;
            sum += bit * bit;
            n = n / 10;
        }
        return sum;
    }
    
    bool isHappy(int n) {
        int slow = n, fast = n;
        do{
            //慢指针走一步
            slow = bitSquareSum(slow);
            //快指针走两步
            fast = bitSquareSum(fast);
            fast = bitSquareSum(fast);
        }while(slow != fast);  
        
        return slow == 1;    //判断是否是因为1导致的循环
    }
};


LeetCode290 easy

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map<string,char> str2ch;  //保存str到ch的映射
        unordered_map<char,string> ch2str;  //保存ch到str的映射

        int m=s.length();  //字符串的长度
        int i=0;  //s的索引
        for(auto ch:pattern)
        {
            if(i>=m)  //pattern还没结束,但是s已经结束
            {
                return false;
            }
            int j=i;  //从i开始找下一个空格或者末尾
            while(j<m && s[j]!=' ')  
                j++;
            string tmp=s.substr(i,j-i); //截取子串
            if(str2ch.count(tmp) && str2ch[tmp]!=ch)  //有别的ch对应tmp
            {
                return false;
            }
            if(ch2str.count(ch) && ch2str[ch]!=tmp)  //ch对应别的tmp
            {
                return false;
            }
            str2ch[tmp]=ch;
            ch2str[ch]=tmp;
            i=j+1;
        }
        return i>=m; 
    }
};


LeetCode205 easy

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1=s.size();
        int len2=t.size();
        if(len1!=len2)  //如果字符串s和t的长度不相等
        {
            return false;
        }
        unordered_map<char,char> s2t;  //s到t的映射
        unordered_map<char,char> t2s;  //t到s的映射
        for(int i=0;i<len1;i++)  //逐个比较
        {
            if(s2t.count(s[i]) && s2t[s[i]] != t[i])  //s[i]对应的不是t[i]
            {
                return false;
            }
            else if(t2s.count(t[i]) && t2s[t[i]]!=s[i]) //t[i]对应的不是s[i]
            {
                return false;
            }
            else
            {                           //添加到map
                s2t[s[i]]=t[i];
                t2s[t[i]]=s[i];
            }
        }
        return true;

    }
};


LeetCode451 medium

方法1:哈希表+排序

struct node{
    char ch;
    int cnt;
    node(){
        ch = '0';
        cnt = 0;
    }
    bool operator<(const node& o)const{
        return cnt > o.cnt;
    }
};

class Solution {
public:
    string frequencySort(string s) {
        vector<node> hash(256);
        for(auto x : s){
            hash[x].ch = x;
            hash[x].cnt++;
        }
        sort(hash.begin(),hash.end());
        string ans;
        for(auto x : hash){
            if(x.cnt){
                ans += string(x.cnt,x.ch);
            }
        }
        return ans;
    }
};

方法2:桶排序

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> map;
        int maxCount(0);
        for (char c: s)
            maxCount = max(maxCount, ++map[c]);

        vector<vector<int>> buckets(maxCount + 1);
        for (auto i(map.begin()); i != map.end(); i++)
            buckets[i->second].push_back(i->first);

        string ans;
        //有maxCount个频次桶
        for (int i(maxCount); i >= 1; i--)
            //对频次桶里的元素进行遍历,换言之,这个桶里的元素频次一样
            for (int j(0); j < buckets[i].size(); j++) {
                //把这个字母放到ans中i次,也就是频次次
                for (int z(0); z < i; z++)
                    ans.push_back(buckets[i][j]);
            }
        return ans;
    }
};

 

 

 


http://www.niftyadmin.cn/n/1032284.html

相关文章

4-4查找表

目录 LeetCode1 easy LeetCode15 medium LeetCode18 medium ​​​​LeetCode16 medium LeetCode1 easy 方法1&#xff1a;暴力 class Solution { public:vector<int> twoSum(vector<int>& nums, int target) {vector<int> res;for(int i0;i<nu…

4-5

LeetCode454 class Solution { public:int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {int ans0;unordered_map<int,int> um; //设置查找表for(int i0;i<C.size();i){for(int j0;j<…

LeetCode 146 LRU缓存机制

方法1&#xff1a;利用C自带的双向链表list和散列表unordered_map class LRUCache { public:LRUCache(int capacity) : cap(capacity) { //构造函数}int get(int key) { if (map.find(key) map.end()) return -1; //找不到&#xff0c;返回-1 &#xff08;使用哈希表提…

LeetCode460 LFU缓存

struct Node { //双向链表的节点int key; //键int val; //值int freq; //频率Node* prev; //前一个节点Node* next; //后一个节点//无参构造函数Node () : key(-1), val(-1), freq(0), prev(nullptr), next(nullptr) {}//带参构造函数Node (int _k, int _v) : key(_k…

动态规划II

目录 力扣343 整数拆分 方法1&#xff1a;动态规划 力扣279.完全平方数 方法1&#xff1a;动态规划 力扣343 整数拆分 方法1&#xff1a;动态规划 class Solution { public: int max3(int x,int y,int z) {return max(x,max(y,z));//return x>y?x:(y>z?y:z); /…

剑指offer 09 两个栈实现队列

思路&#xff1a; 入队时&#xff0c;直接进到A中 出队时&#xff0c;看B是否为空&#xff0c;若不是空&#xff0c;直接从B弹出结果 否则&#xff0c;看A是否为空&#xff0c;如果为空&#xff0c;说明目前没有元素&#xff0c;返回-1 否则&#xff0c;将A中的元素逐个出栈…

树相关

目录 LeetCode104.二叉树的最大深度 方法1&#xff1a;递归 方法2&#xff1a;层序遍历 LeetCode 559.N叉树的最大深度 方法1&#xff1a;递归 方法2&#xff1a;层序遍历 剑指offer 55-II 平衡二叉树 方法1&#xff1a;递归 LeetCode104.二叉树的最大深度 二叉树的最…

剑指offer 54、二叉搜索树的第k大节点

方法1&#xff1a;中序反向遍历&#xff0c;找到后还会继续遍历 class Solution { public:int kthLargest(TreeNode* root, int k) {int result 0;dfs(root, result, k);return result;}private:void dfs(TreeNode *root, int &result, int &k) {if (!root) return;d…