-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianFinder.java
More file actions
60 lines (48 loc) · 1.32 KB
/
MedianFinder.java
File metadata and controls
60 lines (48 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package Leetcode;
import java.util.PriorityQueue;
class MedianFinder
{
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>( ( a, b ) -> b - a );
/** initialize your data structure here. */
public MedianFinder()
{
}
public void addNum( int num )
{
if( maxHeap.isEmpty() )
maxHeap.add( num );
else if( num < maxHeap.peek() )
{
maxHeap.add( num );
if( maxHeap.size() - minHeap.size() == 2 )
{
minHeap.add( maxHeap.remove() );
}
}
else
{
minHeap.add( num );
if( minHeap.size() - maxHeap.size() == 2 )
{
maxHeap.add( minHeap.remove() );
}
}
}
public double findMedian()
{
if( minHeap.size() > maxHeap.size() )
return minHeap.peek();
if( maxHeap.size() > minHeap.size() )
return maxHeap.peek();
return ( minHeap.peek() + maxHeap.peek() ) / 2.0;
}
public static void main( String[] args )
{
MedianFinder obj = new MedianFinder();
obj.addNum( 1 );
obj.addNum( 2 );
double param_2 = obj.findMedian();
System.out.println( param_2 );
}
}