中位数操作
来源:互联网 发布:mac上的邮箱怎么设置 编辑:程序博客网 时间:2024/05/22 03:05
本题源自leetcode
---------------------------------------------------
思路 用俩个优先队列存储。 优先队列 是按降序排列的
1 当 加入一个数字时。先把数字加入小的队列中。然后弹出小队列的队头,并把其相反数压入大的队列。如果小队列的个数小于大队列。就把大的队列头弹栈,取反后压入小的。
2 这样就保证了,如果小的个数大于大的个数,则为奇数,切中位数在小队列的队头。否则就是偶数。中位数是小堆头加上取反的大队头求平均数
代码:
class MedianFinder { priority_queue<int> small,large;public: /** initialize your data structure here. */ MedianFinder() { } void addNum(int num) { small.push(num); large.push(-small.top()); small.pop(); if (small.size() < large.size()) { small.push(-large.top()); large.pop(); } } double findMedian() { return small.size() > large.size() ? small.top() : (small.top() - large.top()) / 2.0; }};
阅读全文
0 0
- 中位数操作
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 第10周项目1(4)哈夫曼编码的算法验证
- 利用nginx搭建RTMP视频点播、直播、HLS服务器
- 第11周项目1-图基本算法库
- sparkSQL详解
- 第十二周项目1-最小生成树的普里姆算法
- 中位数操作
- 第十周项目二C/C++用二叉树求解代数表达式
- 一则count(*) count(1) 为啥没有走索引的遭遇
- dircolors配置,linux目录颜色配置ls
- 服务的卸载
- Java并发编程之synchronized
- 第12周项目2-Kruskal算法的验证
- 第十二周 项目3-Dijkstra算法的验证
- 运行时异常一般异常的区别