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

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();
    }
}

相关推荐

  1. 215. 数组K元素

    2024-04-24 13:00:02       45 阅读
  2. 215数组K元素

    2024-04-24 13:00:02       28 阅读
  3. leetcode-215-数组K元素

    2024-04-24 13:00:02       27 阅读
  4. LeetCode215. 数组K元素

    2024-04-24 13:00:02       14 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-24 13:00:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-24 13:00:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-24 13:00:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-24 13:00:02       18 阅读

热门阅读

  1. React vs React Native写法上的不同

    2024-04-24 13:00:02       14 阅读
  2. 20240423-线程基础

    2024-04-24 13:00:02       13 阅读
  3. C++orm使用插曲——MySQL保留字

    2024-04-24 13:00:02       16 阅读
  4. 如何在 Docker 和 DigitalOcean Kubernetes 上部署 Kafka

    2024-04-24 13:00:02       10 阅读
  5. 深入理解Kubernetes:kube-scheduler源码解析

    2024-04-24 13:00:02       13 阅读
  6. DNS 服务器不同类型有什么作用?

    2024-04-24 13:00:02       15 阅读
  7. 项目开发的详细步骤(精华版)

    2024-04-24 13:00:02       12 阅读
  8. FlinkSQL State的生命周期

    2024-04-24 13:00:02       11 阅读