

Leetcode 295. Find Median from Data Stream
source link: https://zxs.io/article/1328
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在一个有序数组中找中位数,但需要支持再数组中添加新的元素。本来是有序里的,可以很轻易就查到中位数,但如果添加新数字后,不一定有序。如果先对数组排序,那代价就比较大了,每次排序时间复杂度O(n*log(n)),看discuss发现了一种很巧妙的解法,可以把添加数据的时间复杂度降低到O(log(n)) ,查询中位数O(1)。
这里我们需要用到优先队列,java里有现场的优先队列。准备两个优先队列,large里存比中位数大的数,small里存比中位数小的数。加入现在有n个数,large里存最大的n/2个数,很容易理解。但small里怎么存最小的n/2个数? 这里有个很巧妙的地方,把数组里数取负存到small里,small优先队列里其实存的是数组中取负后最大的n/2个数,不就是原数组中最小的n/2个数吗?需要特别考虑到n位奇数时,large里存了n/2+1个数,small里存了n/2个数(其实多余的一个也存small里)。算中位数的时候,如果n为奇数,直接从large里去第一优先级的就好了,如果n是偶数,从large和small里各取一个求平均,注意small里取出的数要取负变换之后才能用。
代码如下,
import java.util.PriorityQueue;
import java.util.Queue;
class MedianFinder {
private Queue<Long> small = new PriorityQueue();
private Queue<Long> large = new PriorityQueue();
/** initialize your data structure here. */
public MedianFinder() {
}
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;
}
}
Recommend
-
12
Leetcode 4. Median of Two Sorted Arrays 当前位置:XINDOO > 编程 > 正文 题目链...
-
8
LeetCode 第 295 号问题:数据流的中位数-程序员小吴 当前位置:程序员小吴 > LeetCodeAnimation > LeetCode 第 295 号问题:数据流的中位数
-
5
IAF to get 56 Airbus C-295 aircraft in a ₹20,000 crore deal September 24, 2021
-
6
园长百万美金之旅之295:国庆第三天-跨境头条-AMZ123亚马逊导航-跨境电商出海门户 园长百万美金之旅之295:国庆第三天...
-
4
About this Episode What to do when there are new APIs that improve but don't deprecate old ones? Do you throw away your old code? Write compatibility layers? Or do you just keep on with what you ha...
-
21
Leetcode 4 寻找两个正序数组的中位数 ( Median of Two Sorted Arrays *Hard* ) 题解分析 发表于 2022-03-27 分类于 Java , lee...
-
7
Codeforces Round #295 Editorial (now with bonuses!) Codeforces Round #295 Editorial (now with bonuses!)
-
7
Sep 14, 2022 — 15:12 CUT AppStories, Episode 295 – iOS 16: The MacStories Review ...
-
4
派能科技:第三季度净利3.81亿元,同比增295% 派能科技发布2022年第三季度报告,公司实现营业收入17.15亿元,同比增长179.71%;归属于上市公司股东的净利润3.81亿元,同比增长295.72%。 ...
-
6
这里记录每周值得分享的科技内容,周五发布。([通知] 下周清明节假期,周刊暂停一次。) 本杂志
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK