215. 数组中的第K个最大元素


215. 数组中的第 K 个最大元素

class Solution {
    public int findKthLargest(int[] nums, int k) {
        int heapSize = nums.length;
        buildMaxHeap(nums, heapSize);
        for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {
            swap(nums, 0, i);
            --heapSize;
            maxHeapify(nums, 0, heapSize);
        }
        return nums[0];
    }

    public void buildMaxHeap(int[] a, int heapSize) {
        for (int i = heapSize / 2; i >= 0; --i) {
            maxHeapify(a, i, heapSize);
        }
    }

    public void maxHeapify(int[] a, int i, int heapSize) {
        int l = i * 2 + 1, r = i * 2 + 2, largest = i;
        if (l < heapSize && a[l] > a[largest]) &#123;
            largest = l;
        &#125;
        if (r < heapSize && a[r] > a[largest]) &#123;
            largest = r;
        &#125;
        if (largest != i) &#123;
            swap(a, i, largest);
            maxHeapify(a, largest, heapSize);
        &#125;
    &#125;

    public void swap(int[] a, int i, int j) &#123;
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    &#125;
&#125;

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/solution/shu-zu-zhong-de-di-kge-zui-da-yuan-su-by-leetcode-/

文章作者:   future
版权声明:   本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 future !
  目录