215. Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: You may assume k is always valid, 1 ≤ k ≤ array's length.

// 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

Was this helpful?