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

在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4

思路:

1.用nums[:k]初始化一个大小为k的小顶堆
2.继续遍历nums[k:]后面的元素,如果元素nums[i]比堆顶元素大,那么pop堆顶元素,pushnums[i]即可
3.最终的堆顶元素即是第K个最大元素

import "container/heap"
// An IntHeap is a min-heap of ints.
type IntHeap []int

func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0: n-1]
return x
}

func findKthLargest(nums []int, k int) int {
tmp := IntHeap(nums[:k])
h := &tmp
heap.Init(h)
for i := k; i < len(nums); i++ {
if (*h)[0] < nums[i] {
heap.Pop(h)
heap.Push(h, nums[i])
}

}

return (*h)[0]
}
原文地址:https://www.cnblogs.com/fwdqxl/p/9349240.html