File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
find-median-from-data-stream Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ # Time Complexity: O(nlogn)
3+ # Space Complexity: O(nlogn)
4+
5+ */
6+ class MedianFinder {
7+
8+ private PriorityQueue <Integer > pq1 ; // 1번째 ~ 가운데 원소 (max heap)
9+ private PriorityQueue <Integer > pq2 ; // 가운데+1번째 ~ 마지막 원소 (min heap)
10+
11+ public MedianFinder () {
12+ pq1 = new PriorityQueue <>(Collections .reverseOrder ());
13+ pq2 = new PriorityQueue <>();
14+ }
15+
16+ public void addNum (int num ) {
17+
18+ if (pq1 .size () == pq2 .size ()) {
19+ if (pq1 .peek () == null || pq1 .peek () >= num ) {
20+ pq1 .add (num );
21+ } else {
22+ pq2 .add (num );
23+ pq1 .add (pq2 .poll ());
24+ }
25+ } else {
26+ if (pq1 .peek () == null || pq1 .peek () >= num ) {
27+ pq1 .add (num );
28+ pq2 .add (pq1 .poll ());
29+ } else {
30+ pq2 .add (num );
31+ }
32+ }
33+ }
34+
35+ public double findMedian () {
36+ if (pq1 .size () == pq2 .size ()) {
37+ return (pq1 .peek () + pq2 .peek ()) / 2.0 ;
38+ } else {
39+ return pq1 .peek ();
40+ }
41+ }
42+ }
43+
44+ /**
45+ * Your MedianFinder object will be instantiated and called as such:
46+ * MedianFinder obj = new MedianFinder();
47+ * obj.addNum(num);
48+ * double param_2 = obj.findMedian();
49+ */
You can’t perform that action at this time.
0 commit comments