方案(一):使用快速排序对给定的数据进行排序,然后从中获取出第K大小的数据;
方案(二):创建一个大小为k的堆结构;
1、h
中没有元素,不变式成立。
2、在迭代过程中,根据h
的元素数量,分为如下两种情况:
3、如果h
中元素的个数小于k
,直接将本次迭代的数组元素num
加入到h
中。
4、如果h
中元素的个数大于等于k
,则需要比较当前h
中,最小的元素是否大于num
,若是,忽略num
的处理,否则,将其替换为num
。 以上两种情况的结果均可以保证不变式成立。
6、nums
中的所有元素均被遍历后算法终止,不变式成立。
代码如下
package main
import (
"container/heap" // 对任意实现了heap接口的类型提供堆操作;
"fmt"
)
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) Top() int {
return h[0]
}
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 {
h := &IntHeap{}
heap.Init(h)
for _, num := range nums {
if h.Len() < k {
heap.Push(h, num)
} else if (*h)[0] < num {
heap.Pop(h)
heap.Push(h, num)
}
}
return heap.Pop(h).(int)
}
func main() {
var arr = []int{1, 3, 5, 2, 2}
var k = int(2)
res := findKthLargest(arr, k)
fmt.Println(res)
}