295. Find Median from Data Stream***
来源:互联网 发布:网络成瘾的影响 编辑:程序博客网 时间:2024/05/20 05:06
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
Examples:[2,3,4]
, the median is 3
[2,3]
, the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
- void addNum(int num) - Add a integer number from the data stream to the data structure.
- double findMedian() - Return the median of all elements so far.
For example:
addNum(1)addNum(2)findMedian() -> 1.5addNum(3) findMedian() -> 2
class MedianFinder { private Queue<Long> small = new PriorityQueue(), large = new PriorityQueue(); public void addNum(int num) { large.add((long) num); small.add(-large.poll()); if (large.size() < small.size()) large.add(-small.poll()); } public double findMedian() { return large.size() > small.size() ? large.peek() : (large.peek() - small.peek()) / 2.0; }};总结:机智哭了,不过可以用binarysearch做,随时插入。两次比较是为了保证新加入的元素和前半部分和后半部分都要比较,而不是一半。
0 0
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- Leetcode 295. Find Median from Data Stream
- Leetcode - 295. Find Median From Data Stream
- [leetcode] 295. Find Median from Data Stream
- LeetCode 295. Find Median from Data Stream
- leetcode 295. Find Median from Data Stream
- LeetCode 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- leetcode.295. Find Median from Data Stream
- 295. Find Median from Data Stream
- [leetcode] 295. Find Median from Data Stream
- [LeetCode]--295. Find Median from Data Stream
- leetcode:295. Find Median from Data Stream
- leetcode 295.Find Median from Data Stream
- [hard]295. Find Median from Data Stream
- 295. Find Median from Data Stream
- 295. Find Median from Data Stream
- Java操作XML文件的例子
- 最近找java实习面试被问到的东西总结(Java方向)
- 尾递归优化
- [jvm][面试]JVM 调优总结
- PHP定时任务实现和Linux crontab定时任务
- 295. Find Median from Data Stream***
- 【CodeForces 779A】Pupils Redistribution(模拟)
- bash: sqlplus: command not found 解决方法
- unity 2D中常见的角色移动同时防止角色二段跳
- Find Bottom Left Tree Value
- Android属性allowBackup安全风险浅析
- 【Activiti工作流】4.准备开发环境(配置文件)和核心api的介绍
- 00003 不思议迷宫.0010.1.1:csb解析显示
- Android开发之在不同API上遇见的坑