File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.PriorityQueue
2
+ class MedianFinder () {
3
+ // 1 2 3 4 5
4
+ // 중간값을 기준으로
5
+ // 3
6
+ // 2 4
7
+ // 1 5
8
+ // 1 2 : maxHeap
9
+ // 4 5 : minHeap
10
+ private val maxHeap = PriorityQueue <Int > { a, b -> b - a }
11
+ private val minHeap = PriorityQueue <Int >()
12
+
13
+ // TC: O(log n)
14
+ // SC: O(n)
15
+ fun addNum (num : Int ) {
16
+ if (maxHeap.isEmpty() || maxHeap.peek() >= num) {
17
+ maxHeap.add(num)
18
+ } else {
19
+ minHeap.add(num)
20
+ }
21
+
22
+ if (maxHeap.size > minHeap.size + 1 ) {
23
+ minHeap.add(maxHeap.poll())
24
+ } else if (minHeap.size > maxHeap.size) {
25
+ maxHeap.add(minHeap.poll())
26
+ }
27
+ }
28
+
29
+ fun findMedian (): Double {
30
+ if (maxHeap.size == minHeap.size) {
31
+ return (maxHeap.peek() + minHeap.peek()) / 2.0
32
+ } else {
33
+ return maxHeap.peek().toDouble()
34
+ }
35
+ }
36
+
37
+ }
You can’t perform that action at this time.
0 commit comments