Advertisement
knakul853

Untitled

Jul 24th, 2020
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. class MedianFinder {
  2. public:
  3.     /** initialize your data structure here. */
  4.    
  5.     priority_queue<int>large;
  6.     priority_queue<int, vector<int>, greater<int>>small;
  7.  
  8.     MedianFinder() {
  9.      
  10.        
  11.     }
  12.    
  13.     void addNum(int num) {
  14.      
  15.         small.push(num);
  16.         large.push(small.top());
  17.         small.pop();
  18.        
  19.         if(small.size() < large.size()){
  20.             small.push(large.top());
  21.             large.pop();
  22.         }
  23.        
  24.     }
  25.    
  26.     double findMedian() {
  27.        
  28.        if(small.size() > large.size())
  29.            return small.top();
  30.         else{
  31.             return (small.top() + large.top())*1.0/2;
  32.         }
  33.        
  34.     }
  35. };
  36.  
  37. /**
  38.  * Your MedianFinder object will be instantiated and called as such:
  39.  * MedianFinder* obj = new MedianFinder();
  40.  * obj->addNum(num);
  41.  * double param_2 = obj->findMedian();
  42.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement