2020.4.2 学习记录

队列,有如下几种:

#include <queue>    //普通队列

#include <deque>    //双端队列

#include <priority_queue> //优先级队列

常规队列操作:

queue.size();   //获取大小
queue.push(x); //入队
queue.pop(); //出队
queue.front(); //头
queue.back(); //尾

双端队列:

queue.push_back();    //队尾插入元素

queue.pop_back();      //队尾删除元素

queue.push_front();    //队头

queue.pop_back();     //队头

优先级队列:

大佬的漫画解析很清晰:

https://www.sohu.com/a/256022793_478315

优先级队列使用堆排序,可以自定义排序规则,也就是说可以自己写cmp,比如说想实现map的按照value值排序,可以写如下代码:

扫描二维码关注公众号,回复: 10402673 查看本文章
struct cmp{
        bool operator()(pair<char,int> x,pair<char,int> y){
            return x.second < y.second;
        }        
};
priority_queue<pair<char,int>,vector<pair<char,int>>,cmp> q;

在上面的代码中,cmp实现的是大顶堆,并且使用数组在存储pair,以此来实现自定义排序的map

最后的队列q是按value值从大到小排序(大顶堆);

 1 struct cmp{
 2         bool operator()(pair<char,int> x,pair<char,int> y){
 3             return x.second < y.second;
 4         }        
 5 };
 6 priority_queue<pair<char,int>,vector<pair<char,int>>,cmp> q;
 7 //在上面的代码中,cmp实现的是大顶堆,并且使用数组在存储pair,以此来实现自定义排序的map
 8 
 9 //最后的队列q是按value值从大到小排序(大顶堆);
10 
11 //leetcode 767题重构字符串
12 #include <bits/stdc++.h>
13 using namespace std;
14 class Solution {
15 public:
16     struct cmp{
17         bool operator()(pair<char,int> x,pair<char,int> y){
18             return x.second < y.second;
19         }
20     };
21 
22     string reorganizeString(string S) {
23         int n = S.length();
24         priority_queue<pair<char,int>,vector<pair<char,int>>,cmp> q;
25         unordered_map<char,int> mp;
26         for(char c : S){
27             mp[c]++;
28         }
29         string res = "";
30         char pre = ' ';
31         for(auto i : mp){
32             pair<char,int> pa;
33             pa.first = i.first;
34             pa.second = i.second;
35             q.push(pa);
36         }
37         stack<pair<char,int>> stk;
38         while(!q.empty()){
39             while(!q.empty() && q.top().first == pre){
40                 stk.push(q.top());
41                 q.pop();
42             }
43             if(q.empty()) return "";
44             pre = q.top().first;
45             int n = q.top().second;
46             res += pre;
47             q.pop();
48             if(--n != 0) q.push(make_pair(pre,n));
49             while(!stk.empty()){
50                 q.push(stk.top());
51                 stk.pop();
52             }
53         }
54         return res;
55     }
56 };
57 int main() {
58     Solution slu;
59     string input;
60     cin >> input;
61     cout << slu.reorganizeString(input);
62  return 0;
63 }

猜你喜欢

转载自www.cnblogs.com/toukome2000/p/12618464.html