Solution:
Just for the purpose of practice, will use min heap data structure to solve this problem. Then the Kth largest element will be the root of a min heap with size of K.
Need to build a min Heap structure, and the key step is a shift function that will be used in both building and maintaining the heap. See below:
Code:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int l = nums.size();
buildMinHeap(nums, k);
for(int i=k; i<l; ++i){
if(nums[i] > nums[0]){
swap(nums[i], nums[0]);
shiftHeap(nums, 0, k-1);
}
}
return nums[0];
}
private:
void buildMinHeap(vector<int> &n, int l){
for(int i=1; i<l; ++i){
n.insert(n.begin(), n[i]);
n.erase(n.begin()+i+1);
shiftHeap(n, 0, i); //maintain an ordered range 0-i;
}
}
void shiftHeap(vector<int> &v, int m, int n){
if(2*m+1 == n && v[m] > v[n]) swap(v[m], v[n]);//if 2*m + 1 > n, continue;
if(2*m+2<=n && v[m] > min(v[2*m+1], v[2*m+2])){
if(v[2*m+1] > v[2*m+2]){
swap(v[m], v[2*m+2]);
shiftHeap(v, 2*m+2, n);
}
else{
swap(v[m], v[2*m+1]);
shiftHeap(v, 2*m+1, n);
}
}
}
};
No comments :
Post a Comment