题单介绍:

精选 100 道力扣(LeetCode)上最热门的题目,适合初识算法与数据结构的新手和想要在短时间内高效提升的人,熟练掌握这 100 道题,你就已经具备了在代码世界通行的基本能力。

目录

题单介绍:

题目:394. 字符串解码 - 力扣(Leetcode)

题目的接口:

解题思路:

代码:

过过过过啦!!!!

题目:347. 前 K 个高频元素 - 力扣(Leetcode)

题目的接口:

解题思路:

代码:

过过过过啦!!!!

写在最后:


题目:394. 字符串解码 - 力扣(Leetcode)

【LeetCode】HOT 100(26)-LMLPHP

题目的接口:

class Solution {
public:
    string decodeString(string s) {

    }
};

解题思路:

看到这种括号匹配的题目,

第一个想法其实就是用栈来解决,

一个栈存储数字,一个栈存储字母,

遇到做括号入栈,遇到右括号就出栈,

根据这个思路来做就行:

代码如下:

代码:

class Solution {
public:
    string decodeString(string s) {
        stack<int> stI;
        stack<string> stS;
        int num = 0;
        string res = "";
        for(int i = 0; i < s.size(); i++) {
            if(s[i] >= '0' && s[i] <= '9') { //数字
                num = num * 10 + (s[i] - '0');
            }
            else if((s[i] >= 'a' && s[i] <= 'z') ||(s[i] >= 'A' && s[i] <= 'Z')) { //字母
                res += s[i];
            }
            else if(s[i] == '[') { //左方括号
                stI.push(num);
                num = 0;
                stS.push(res);
                res = "";
            }
            else { //s[i] == "]"
                int tmp = stI.top();
                stI.pop();
                for(int j = 0; j < tmp; j++) {
                    stS.top() += res;
                }
                res = stS.top();
                stS.pop();
            }
        }
        return res;
    }
};

过过过过啦!!!!

【LeetCode】HOT 100(26)-LMLPHP

题目:347. 前 K 个高频元素 - 力扣(Leetcode)

【LeetCode】HOT 100(26)-LMLPHP

题目的接口:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {

    }
};

解题思路:

很开心很开心,

这道题是我的原创思路解法,总共分三步走:

思路如下:

第一步,用map记录元素出现的次数,并去重;

第二步,然后用优先级队列根据出现的次数排一个降序,让出现次数最多的在最前面;

第三步,从优先级队列里面拿出前k个出现次数最多的数字push进返回数组即可。

代码如下:

代码:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        //第一步,用map记录元素出现的次数,并去重
        map<int, int> mp;
        for(auto e : nums) mp[e]++;

        //第二步,然后用优先级队列根据出现的次数排一个降序,让出现次数最多的在最前面
        priority_queue<pair<int, int>, vector<pair<int,int>>, cmp> pq;
        for(const auto& k : mp) pq.push(k);

        //第三步,从优先级队列里面拿出前k个出现次数最多的数字push进返回数组即可
        vector<int> ans;
        for(int i = 0; i < k; i++) {
            ans.push_back(pq.top().first);
            pq.pop();
        }
        return ans;
    }
    
private:
    class cmp {
    public:
        //根据出现的次数排成降序的排序逻辑(仿函数)
        bool operator()(const pair<int,int>& cp1, const pair<int,int>& cp2) {
            return cp1.second < cp2.second;
        }
    };
};

过过过过啦!!!!

【LeetCode】HOT 100(26)-LMLPHP

写在最后:

以上就是本篇文章的内容了,感谢你的阅读。

如果感到有所收获的话可以给博主点一个哦。

如果文章内容有遗漏或者错误的地方欢迎私信博主或者在评论区指出~

07-10 14:37