主要是priority_queue的用法
一个是内置类型优先队列怎么设置小根堆(默认大根堆)
如果是自定义数据结构,有两种办法
1、定义这种数据结构的比较符号,就可以当成内置类型整
2、传进去一个重载()的类,当小于号用,默认还是大根堆,也许传进去的是个callable object都行的吧,我试了一下函数好像不行,不懂,不管了
LRU Cache
class LRUCache{ public: // @param capacity, an integer int Time; typedef int key; typedef int time; typedef int value; typedef pair<key,time> ktpair; struct cmp { bool operator()(ktpair x1,ktpair x2) { return x1.second > x2.second; } }; map<key,value> kv; map<key,time> kt; priority_queue<ktpair,vector<ktpair>,cmp> q; int Cap; LRUCache(int capacity) { // write your code here Time = 0; Cap = capacity; } void insert(int key,int value,int time) { kv[key] = value; kt[key] = time; q.push(make_pair(key,time)); } // @return an integer int get(int key) { // write your code here Time++; value ret; if (kv.find(key) != kv.end()) { int value = kv[key]; insert(key,value,Time); return value; } else return -1; } // @param key, an integer // @param value, an integer // @return nothing void set(int key, int value) { // write your code here Time++; if (kv.find(key) == kv.end()) { insert(key,value,Time); if (!Cap) { for(;;) { auto x = q.top(); auto ckey = x.first; auto ctime = x.second; q.pop(); if (kt.find(ckey) == kt.end() || kt[ckey] != ctime) continue; else { kv.erase(ckey); kt.erase(ckey); break; } } } else Cap--; } else insert(key,value,Time); } };
Data Stream Median
class Solution { public: /** * @param nums: A list of integers. * @return: The median of numbers */ vector<int> medianII(vector<int> &nums) { // write your code here priority_queue<int,vector<int>,less<int>> q1; priority_queue<int,vector<int>,greater<int>> q2; vector<int> ret; q1.push(INT_MIN); q2.push(INT_MAX); for (auto x : nums) { if (x < q2.top()) q1.push(x); else q2.push(x); if (q1.size() < q2.size()) { q1.push(q2.top()); q2.pop(); } if (q1.size() > 1 + q2.size()) { q2.push(q1.top()); q1.pop(); } ret.push_back(q1.top()); } return ret; } };
时间: 2024-11-08 17:19:20