@@ -448,25 +448,6 @@ double findMedian()
448
448
{
449
449
return sz&1 ? arr[sz/2] : (arr[sz/2 + 1] + arr[sz/2])/2.0;
450
450
}
451
-
452
- // O(logN) using 2 heaps
453
- priority_queue<int > l;
454
- priority_queue<int, vector<int >, greater<int >> r;
455
- void addNum(int num)
456
- {
457
- l.push(num);
458
- r.push(l.top());
459
- l.pop();
460
- if (l.size() < r.size())
461
- {
462
- l.push(r.top());
463
- r.pop();
464
- }
465
- }
466
- double findMedian()
467
- {
468
- return l.size() > r.size() ? l.top() : ((double) l.top() + r.top()) * 0.5;
469
- }
470
451
```
471
452
472
453
* Maintain two heaps i.e. left and right half from middle. We are performing 3 push and 2 pop operations making it total O\(5logN\)
@@ -476,6 +457,7 @@ priority_queue<int> left;
476
457
priority_queue<int, vector<int>, greater<int>> right;
477
458
478
459
MedianFinder() { }
460
+ // LogN Solution
479
461
/* Think 3 steps: sz(left) == sz(right), sz(left) > sz(right), sz(left) < sz(right) */
480
462
void addNum(int num)
481
463
{
@@ -498,20 +480,27 @@ double findMedian()
498
480
* We can use policy based data structure, both insertion and find takes logN & 3logN time here but there's no overhead of inserting 5 times so this might perform better in some scenerios
499
481
500
482
``` cpp
501
- orderedMultiSet st;
502
- int n = 0 ;
483
+ #include < ext/pb_ds/tree_policy.hpp>
484
+ #include < ext/pb_ds/assoc_container.hpp>
485
+ using namespace __gnu_pbds ;
486
+ typedef tree<int , null_type, less_equal<int >, rb_tree_tag, tree_order_statistics_node_update> orderedMultiSet;
503
487
504
- MedianFinder () { }
505
- void addNum(int num)
506
- {
507
- st.insert(num);
508
- n++;
509
- }
510
- double findMedian()
511
- {
512
- return n&1 ? *st.find_by_order(n/2) :
513
- (*st.find_by_order(n/2 - 1) + *st.find_by_order(n/2))/2.0;
514
- }
488
+ class MedianFinder {
489
+ public:
490
+ orderedMultiSet st;
491
+ int n = 0;
492
+
493
+ MedianFinder() { }
494
+ void addNum (int num)
495
+ {
496
+ st.insert(num);
497
+ n++;
498
+ }
499
+ double findMedian()
500
+ {
501
+ return n&1 ? * st.find_by_order(n/2) : (* st.find_by_order(n/2 - 1) + * st.find_by_order(n/2))/2.0;
502
+ }
503
+ };
515
504
```
516
505
517
506
### [Design HashMap](https://leetcode.com/problems/design-hashmap/)
0 commit comments