leetcode703_2-11每日题:数据流中第K大元素

class KthLargest {
     
public:
    int k;
    vector<int> nums;
    KthLargest(int m_k, vector<int>& m_nums):k(m_k),nums(m_nums){
     
       if(!nums.empty()) sort(nums.begin(),nums.end(),greater<int>());
    }
    int add(int val) {
     
       if(nums.empty()) {
     
         nums.push_back(val); 
         return nums[k-1];
       }
       int left=0,right=nums.size()-1;
       while(left<=right){
     
           int mid = (left+right)/2;
           if(nums[mid]>val) left=mid+1;
           else if(nums[mid]==val) {
     
              left = mid;
              break;
           }
           else if(nums[mid]<val){
     
               right = mid;
               if(left==right) break;
           }
       }
       nums.insert(nums.begin()+left,val);
       return nums[k-1];
    }
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */

每次插入时使用2分法。

你可能感兴趣的:(leetcode)