215 Kth Largest Element in an Array

本文介绍了解决LeetCode上Kth最大元素问题的三种方法:使用优先队列(最小堆)、库函数排序以及快速排序。通过具体代码实现展示了不同算法的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/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.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

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

解题思路:
这题的考点是排序。题目给的线索是Heap。
最简单的方法是使用库函数 Arrays.sort() 对数组进行快速排序,获取有序数组的倒数第 K 个元素即可。
其实,自己一开始能想到的是堆排序。题目提示也是 heap。
但,在网上看到别人的做法是使用快速排序,当 pivot 放入倒数第 K 个位置时,当前 pivot 即为第 K 大的元素,排序终止。
再上网查,发现有人用优先队列(最小堆)来求解。
遍历数组时将数字加入优先队列(堆),一旦堆的大小大于k就将堆顶元素去除,确保堆的大小为k。遍历完后堆顶就是返回值。
我想,这种方法才是题目所要考的吧。
参考链接:https://segmentfault.com/a/1190000003704825

代码实现:
使用优先队列:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> p = new PriorityQueue<Integer>();
        for(int i = 0 ; i < nums.length; i++){
            p.add(nums[i]);
            if(p.size()>k) p.poll();
        }
        return p.poll();
    }
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 16 ms

使用库函数:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0)
            return 0;
        Arrays.sort(nums);
        return nums[nums.length - k];
    }
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 4 ms

使用快速排序:

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0)
            return 0;
        return getKth(nums.length - k, nums, 0, nums.length - 1);
    }
    int getKth(int k, int[] nums, int start, int end) {
        int l = start;
        int r = end;
        int pivot = nums[l];
        while(l < r) {
            while(l < r && nums[r] >= pivot) {
                r --;
            }
            nums[l] = nums[r];
            while(l < r && nums[l] <= pivot) {
                l ++;
            }
            nums[r] = nums[l];
        }
        nums[l] = pivot;
        if(l == k) { // l 为此时 pivot 的位置
            return pivot;
        } else if(l < k) { // k 在 此时 pivot 的右侧,对 pivot(l)进行快速排序
            return getKth(k, nums, l + 1, end);
        } else { // k 在 此时 pivot 的左侧侧,对 pivot(r)进行快速排序
            return getKth(k, nums, start, r - 1);
        }
    }
}
31 / 31 test cases passed.
Status: Accepted
Runtime: 52 ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值