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

本文介绍了一种使用Java实现的方法,通过构建一个优先队列(小顶堆)来找到给定数组中的第K个最大元素。算法首先将前k个元素加入堆中,然后遍历剩余元素,如果当前元素大于堆顶元素,则替换堆顶并调整。最后返回堆顶元素即为第K大元素,时间复杂度为O(nlogn),空间复杂度为O(n)。
摘要由CSDN通过智能技术生成

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

题目描述

在这里插入图片描述

思路

1.维护一个小顶堆minHeap,并将数组nums中的前k个元素添加到minHeap中;
2.从nums中k后面的元素开始,若当前nums中的元素大于小顶堆中的堆顶元素,则将其minHeap中堆顶的元素取出,将当前的nums中的元素添加到minHeap中
3.返回最终的minHeap堆顶的元素即为第K大元素;

复杂度

时间复杂度:

O ( n l o g n ) O(nlogn) O(nlogn);其中 n n n是数组的大小

空间复杂度:

O ( n ) O(n) O(n)

Code

class Solution {
    /**
     * Find the KTH largest element in the array
     *
     * @param nums Given array
     * @param k Given number
     * @return int
     */
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k, Comparator.comparingInt(a -> a));
        for (int i = 0; i < k; ++i) {
            minHeap.offer(nums[i]);
        }
        // Starting from k, compare nums[i] with the first element each time
        for (int i = k; i < nums.length; i++) {
            Integer topElement = minHeap.peek();
            // If it is larger than the top of the heap, the top of the heap element
            // is removed from the queue and the top element is rejoined.
            if (nums[i] > topElement) {
                minHeap.poll();
                minHeap.offer(nums[i]);
            }
        }
        // Returns the smallest value in the smallest
        // heap of the largest k elements of the natural order
        return minHeap.peek();
    }
}
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值