Leetcode专题-215-数组中的第K个最大元素

LabRat / 137 /

ChatGPT 可用网址,仅供交流学习使用,如对您有所帮助,请收藏并推荐给需要的朋友。
https://ckai.xyz

leetcode链接:
https://leetcode.cn/problems/kth-largest-element-in-an-array/...
解题思路:
使用一个小顶堆来存储当前已经找到的前k大的数,如果遍历到一个新数时,它比堆顶元素大,那么就弹出堆顶元素,将新数加入堆中,保证堆中始终存储前k大的数。最终返回堆顶元素即可。

import ""container/heap"

type TopList []int

func (t TopList)Len()int{
    return len(t)
}
func (t TopList)Swap(i,j int){
      t[i],t[j] = t[j],t[i]
}
func (t TopList)Less(i,j int)bool{
    return  t[i]<t[j]
}
func (t *TopList)Push(x interface{}){
    *t = append(*t,x.(int))
}
func (t *TopList)Pop()interface{}{
    x := (*t)[len(*t)-1]
    *t= (*t)[:len(*t)-1]
    return x
}


func findKthLargest(nums []int, k int) int {
    m :=make(TopList,0)
    size :=0
    for i:=range nums{
        if size<k{
            heap.Push(&m,nums[i])
            size++
        }else {
            if nums[i]>m[0]{//小顶堆 堆顶元素小于当前元素
                heap.Pop(&m)
                heap.Push(&m,nums[i])
            }
        }
    }
    return m[0]
}

Leetcode专题-215-数组中的第K个最大元素
作者
LabRat
许可协议
CC BY 4.0
发布于
2023-09-02
修改于
2025-02-10
Bonnie image
尚未登录