Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5dfd5d3

Browse files
find median from data stream using two heaps
1 parentea25239 commit5dfd5d3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
packagehard;
2+
3+
importjava.util.*;
4+
5+
/**
6+
* Created by fishercoder1534 on 10/3/16.
7+
*/
8+
publicclassFindMedianFromDataStream {
9+
}
10+
11+
classMedianFinder {
12+
//Thanks to Stefan's post: https://discuss.leetcode.com/topic/27521/short-simple-java-c-python-o-log-n-o-1
13+
/**
14+
* The idea is for sure to use two heaps, one is max heap, one is min heap, we always let the max heap be one element
15+
* bigger than min heap if the total number of elements is not even.
16+
* we could always get the median in O(1) time.
17+
* 1. use Long type to avoid overflow
18+
* 2. negate the numbers for small heap to save the effort for writing a reverse comparator, brilliant!*/
19+
privateQueue<Long>large =newPriorityQueue<Long>();
20+
privateQueue<Long>small =newPriorityQueue<Long>();
21+
22+
// Adds a number into the data structure.
23+
publicvoidaddNum(intnum) {
24+
large.offer((long)num);
25+
small.offer(-large.poll());
26+
if(large.size() <small.size())large.offer(-small.poll());
27+
}
28+
29+
// Returns the median of current data stream
30+
publicdoublefindMedian() {
31+
if(large.size() >small.size())returnlarge.peek();
32+
return (large.peek()-small.peek())/2.0;
33+
}
34+
35+
};
36+
37+
// Your MedianFinder object will be instantiated and called as such:
38+
// MedianFinder mf = new MedianFinder();
39+
// mf.addNum(1);
40+
// mf.findMedian();

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp