Skip to content

Commit c59747e

Browse files
committed
find median from data stream solution
1 parent 11c1853 commit c59747e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.PriorityQueue;
2+
3+
class MedianFinder {
4+
5+
// μž‘μ€ 수 λ²”μœ„ μ €μž₯ν•˜λŠ” νž™
6+
private PriorityQueue<Integer> smallHeap;
7+
8+
// 큰 수 λ²”μœ„ μ €μž₯ν•˜λŠ” νž™
9+
private PriorityQueue<Integer> largeHeap;
10+
11+
public MedianFinder() {
12+
smallHeap = new PriorityQueue<>((a, b) -> b - a);
13+
largeHeap = new PriorityQueue<> ((a, b) -> a - b);
14+
}
15+
16+
public void addNum(int num) {
17+
// μž‘μ€ 수 λ²”μœ„μ— μ‚½μž…
18+
smallHeap.offer(num);
19+
// μž‘μ€ 수 λ²”μœ„μ—μ„œ μ΅œλŒ“κ°’μ„ 뽑아 큰 수 λ²”μœ„λ‘œ 이동
20+
largeHeap.offer(smallHeap.poll());
21+
22+
// λ§Œμ•½ μž‘μ€ 수 λ²”μœ„μ˜ κ°œμˆ˜κ°€ 큰 수 λ²”μœ„λ³΄λ‹€ μž‘λ‹€λ©΄
23+
if (smallHeap.size() < largeHeap.size()) {
24+
// 큰 수 λ²”μœ„μ—μ„œ μ΅œμ†Ÿκ°’μ„ 뽑아 μž‘μ€ 수 λ²”μœ„λ‘œ 이동
25+
smallHeap.offer(largeHeap.poll());
26+
}
27+
}
28+
29+
public double findMedian() {
30+
// 짝수 개일 경우
31+
if (smallHeap.size() == largeHeap.size()) {
32+
// μž‘μ€ 수 λ²”μœ„ νž™μ˜ μ΅œλŒ“κ°’ + 큰 수 λ²”μœ„ νž™μ˜ μ΅œμ†Ÿκ°’μ˜ 평균
33+
return (smallHeap.peek() + largeHeap.peek()) / 2.0;
34+
}
35+
// μž‘μ€ 수 λ²”μœ„ νž™μ˜ μ΅œλŒ“κ°’
36+
return smallHeap.peek();
37+
}
38+
}
39+
40+
/**
41+
* Your MedianFinder object will be instantiated and called as such:
42+
* MedianFinder obj = new MedianFinder();
43+
* obj.addNum(num);
44+
* double param_2 = obj.findMedian();
45+
*/
46+

0 commit comments

Comments
Β (0)