优先队列能够用堆来实现, 堆底层能够用数组表示,
经过索引关系,能够表示成一颗二叉彻底树数组
C++的STL提供了相应的容器适配器
包含在queue
头文件中less
下面经过一道题来看如何使用它spa
string frequencySort(string s) { }
首先,统计字符出现的频率,经过map容器能够很简单的统计出来code
map<char, int> mp; for (auto e : s) { ++mp[e]; }
而后咱们须要构建一个优先队列,并且要指定优先队列的排序方式
所以咱们定义了一个本身的结构体, 并定义了<
操做符(降序定义小于号,升序大于号),排序
struct Node { Node(const pair<char, int> &val) : p(val) {} pair<char, int> p; }; bool operator<(const Node &a, const Node &b) { return a.p.second < b.p.second; }
而后把键值对放入优先队列中索引
priority_queue<Node, vector<Node>, less<Node>> pq; for (auto e : mp) { pq.push(make_pair(e.first, e.second)); }
要用的时候,依次取出来就是了,每次取出的都是里面最大(或最小)的队列
string res; while (!pq.empty()) { for (int i = 0; i < pq.top().p.second; ++i) res.push_back(pq.top().p.first); pq.pop(); }
还有好几个相似的题,均可以用这种方式解决ip
好比 :ci
#include <vector> using namespace std; template <class T> class Heap { public: Heap(size_t maxElems) { h = new HeapStruct; h->Elems = new T[maxElems + 1]; h->Capacity = maxElems; h->size = 0; } ~Heap() { destroy(); } void insert(T x) { size_t i; if (isFull()) { return; } for (i = ++h->size; i / 2 > 0 && h->Elems[i / 2] > x; i /= 2) { h->Elems[i] = h->Elems[i / 2]; } h->Elems[i] = x; } T deleteMin() { size_t i, child; T minElems, lastElems; if (isEmpty()) return h->Elems[0]; minElems = h->Elems[1]; lastElems = h->Elems[h->size--]; for (i = 1; i * 2 <= h->size; i = child) { child = i * 2; if (child != h->size && h->Elems[child + 1] < h->Elems[child]) ++child; if (lastElems > h->Elems[child]) h->Elems[i] = h->Elems[child]; else break; } h->Elems[i] = lastElems; return minElems; } bool isFull() { return h->size == h->Capacity; } bool isEmpty() { return h->size == 0; } T findMin() { return h->Elems[1]; } private: void destroy() { delete h->Elems; delete h; } void makeEmpty() {} struct HeapStruct { size_t Capacity; size_t size; T *Elems; }; HeapStruct* h; };