力扣练习之数组中的第K个最大元素

我爱海鲸 2023-03-23 18:16:09 暂无标签

简介中级算法、排序和搜索

原图出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xvsehe/

解法一:

class Solution {
    public int findKthLargest(int[] nums, int k) {
    Arrays.sort(nums);
    return nums[nums.length - k];
    }
}

思路:从小到大排序,然后从后面开始获取数组元素即可。

解法二:

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
        for (int num : nums) {
            queue.add(num);
            if (queue.size() > k) {
                queue.poll();
            }
        }
        return queue.peek();
    }
}

思路:最小堆解决问题,将数组放到最小堆中,如果堆中的元素大于k,就将堆顶出栈,之后我们只需要取出堆顶元素就是我们想要的值。

 

你好:我的2025