其他分享
首页 > 其他分享> > 数组中的第K个最大元素(来源力扣)(快速排序、堆排序)

数组中的第K个最大元素(来源力扣)(快速排序、堆排序)

作者:互联网

给定整数数组 nums 和整数 k,请返回数组中第 k 个最大的元素。

请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

方法一:基于快速排序的选择方法

class Solution {
    Random random = new Random();
    public int findKthLargest(int[] nums, int k) {
        return quickSort(nums, 0, nums.length - 1, nums.length - k);
    }
    public int quickSort(int[] a, int l ,int r, int index) {
        int q = randomPartition(a, l, r);
        if(q == index)
            return a[q];
        else
            return  q < index ? quickSort(a, q + 1, r, index) :quickSort(a, l, q - 1, index);
    }
    private int randomPartition(int[] a, int l ,int r) {
        int i = random.nextInt(r - l + 1) + l;
        swap(a, i, r);
        return partition(a, l, r);
    }
    private int partition(int[] a, int l, int r) {
        int x = a[r], i = l;
        for(int j = l; j < r ;j++) {
            if(a[j] <= x)
                swap(a, i++, j);
        }
        swap(a, i, r);
        return i;
    }
    private void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

总结:快速排序的时间复杂度为O( nlogn );当加入了随机变量后,其时间复杂度为O( n );

方法二:基于堆排序的选择方法

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]) {
            largest = l;
        } 
        if (r < heapSize && a[r] > a[largest]) {
            largest = r;
        }
        if (largest != i) {
            swap(a, i, largest);
            maxHeapify(a, largest, heapSize);
        }
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

时间复杂度为O( nlogn )

标签:index,nums,int,堆排序,力扣,heapSize,largest,排序,public
来源: https://blog.csdn.net/qq_53198408/article/details/122461019