Title description
Solve the small root heap to solve the TOP K problem
Small root pile solves TOP K ideas:
Find the minimum
First build a large root pile , and then press k numbers
. Each remaining number is first pressed, and then the top element
of the pile is popped. After all the elements are pressed, the top of the pile is the k-th smallest number.
Find the maximum
First create a small root heap , and then press k numbers
. Each remaining number is first pressed, and then the top element
of the heap is popped. After all the elements are pressed, the top of the heap is the k-th largest number
ps: C++ defaults to the big root heap. Here you can remember the wording of the root of the big and small
- Little with greater
-
priority_queue<int, vector<int>, greater<int>> q;
- Radish less
-
priority_queue<int, vector<int>, less<int>> q;
class KthLargest {
public:
//小根堆 堆首取第k大元素
priority_queue<int, vector<int>, greater<int>> q;
int k;
KthLargest(int k, vector<int>& nums) {
this -> k = k;
this -> q = priority_queue<int, vector<int>, greater<int>> (nums.begin(), nums.end());
}
int add(int val) {
q.push(val);
if(q.size() < k) return NULL;
while(q.size() > k) {
q.pop();
}
return q.top();
}
};
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest* obj = new KthLargest(k, nums);
* int param_1 = obj->add(val);
*/
Time complexity O(1) Average complexity of add function
Space complexity O(n)