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

题目描述

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

image-20230306225614142

class Solution {
    public int findKthLargest(int[] nums, int k) {
        // 最小堆,堆顶是当前 top-k 中最小值
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();

        for (int num : nums) {
            minHeap.offer(num);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }

        return minHeap.peek();
    }
}
type MinHeap []int

func (h MinHeap) Len() int           { return len(h) }
func (h MinHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h MinHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *MinHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}

func (h *MinHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[:n-1]
	return x
}

func findKthLargest(nums []int, k int) int {
	h := &MinHeap{}
	heap.Init(h)

	for _, num := range nums {
		heap.Push(h, num)
		if h.Len() > k {
			heap.Pop(h)
		}
	}

	return (*h)[0]
}

相似题目

题目 难度 考察点
324. 摆动排序 II 中等 排序、分治
347. 前 K 个高频元素 中等 堆、哈希表
414. 第三大的数 简单 排序、集合
703. 数据流中的第 K 大元素 简单
973. 最接近原点的 K 个点 中等 堆、快速选择
1985. 找出数组中的第 K 大整数 中等 堆、快速选择
2099. 找到和最大的长度为 K 的子序列 简单 堆、排序
2146. 价格范围内最高排名的 K 样物品 中等 BFS、堆
912. 排序数组 中等 排序
295. 数据流的中位数 困难 双堆
本文作者:
本文链接: https://hgnulb.github.io/blog/2026/17103515
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!