【Lintcode】LRU Cache, Data Stream Median
2016-02-21 21:16
429 查看
主要是priority_queue的用法
一个是内置类型优先队列怎么设置小根堆(默认大根堆)
如果是自定义数据结构,有两种办法
1、定义这种数据结构的比较符号,就可以当成内置类型整
2、传进去一个重载()的类,当小于号用,默认还是大根堆,也许传进去的是个callable object都行的吧,我试了一下函数好像不行,不懂,不管了
LRU Cache
Data Stream Median
一个是内置类型优先队列怎么设置小根堆(默认大根堆)
如果是自定义数据结构,有两种办法
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; } };
相关文章推荐
- OpenCV学习06
- JavaWeb----JDBC
- UDL ODBC 获取数据库连接字符串
- 数组最大值放中间,其他依次放其左右
- java内存分析,栈内存,堆内存
- 局部变量,静态局部变量,全局变量,静态全局变量在内存中的存放区别
- 托管Dll动态调用
- ImageView中src和background属性的主要亮点区别
- 引用作形參--输入三个整数,按从大到小排序
- OS快捷键
- 科学计算软件——Octave安装
- jQuery
- LeetCode35. Search Insert Position轻松解决
- mysql学习笔记(1)
- 设计模式——适配器模式
- C++Primer charpter1.
- 全面理解Context
- Ubuntu下挂载win7的磁盘分区
- 已知四边形四个顶点坐标,求面积
- POJ 2195(二分图最大权匹配)