215. Kth Largest Element in an Array
Input: [3,2,1,5,6,4] and k = 2
Output: 5Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4// HeapSort
// Repeatedly remove the largest element from the heap (the root of the heap), and insert it into the array.
// Heapify procedure can be applied to a node if its children nodes are heapified.
void heapify(vector<int>& nums, int heap_size, int i) { // time: O(nlogn); space: O(1)
int largest = i;
int left = 2 * largest + 1, right = 2 * largest + 2;
if (left < heap_size && nums[left] > nums[largest]) largest = left;
if (right < heap_size && nums[right] > nums[largest]) largest = right;
if (largest != i) {
swap(nums[i], nums[largest]);
heapify(nums, heap_size, largest); // tail recursion
}
}
int findKthLargest(vector<int>& nums, int k) {
int heap_size = nums.size();
for (int i = heap_size / 2 - 1; i >= 0; --i) {
heapify(nums, heap_size, i);
}
for (int i = 0; i < k; ++i) {
swap(nums[0], nums[heap_size - 1]);
--heap_size;
heapify(nums, heap_size, 0);
}
return nums[heap_size];
}Last updated