knakul853

Untitled

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