You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
func findKthLargest(nums []int, k int) int {
// 小顶堆,堆顶是最小元素
pq := priorityQueue{}
for _, e := range nums {
// 每个元素都要过一遍二叉堆
pq.offer(e)
// 堆中元素多于 k 个时,删除堆顶元素
if pq.size() > k {
pq.poll()
}
}
// pq 中剩下的是 nums 中 k 个最大元素,
// 堆顶是最小的那个,即第 k 个最大元素
return pq.peek()
}
type priorityQueue []int
func (pq *priorityQueue) Len() int { return len(*pq) }
请在提交 bug 之前先搜索
出错的题目链接
https://leetcode.cn/problems/kth-largest-element-in-an-array/
报错信息
`
// 注意:go 代码由 chatGPT🤖 根据我的 java 代码翻译,旨在帮助不同背景的读者理解算法逻辑。
// 本代码不保证正确性,仅供参考。如有疑惑,可以参照我写的 java 代码对比查看。
func findKthLargest(nums []int, k int) int {
// 小顶堆,堆顶是最小元素
pq := priorityQueue{}
for _, e := range nums {
// 每个元素都要过一遍二叉堆
pq.offer(e)
// 堆中元素多于 k 个时,删除堆顶元素
if pq.size() > k {
pq.poll()
}
}
// pq 中剩下的是 nums 中 k 个最大元素,
// 堆顶是最小的那个,即第 k 个最大元素
return pq.peek()
}
type priorityQueue []int
func (pq *priorityQueue) Len() int { return len(*pq) }
func (pq *priorityQueue) Less(i, j int) bool { return (*pq)[i] < (*pq)[j] }
func (pq *priorityQueue) Swap(i, j int) { (*pq)[i], (*pq)[j] = (*pq)[j], (*pq)[i] }
func (pq *priorityQueue) Push(x interface{}) { *pq = append(*pq, x.(int)) }
func (pq *priorityQueue) Pop() interface{} {
old := *pq
n := len(old)
x := old[n-1]
*pq = old[0 : n-1]
return x
}
func (pq *priorityQueue) offer(e int) { heap.Push(pq, e) }
func (pq *priorityQueue) poll() int { return heap.Pop(pq).(int) }
func (pq *priorityQueue) peek() int { return (*pq)[0] }
`
报错信息在 if pq.size() > k { 改成 if pq.Len() > k {
你是否愿意提交 PR 修复这个 bug?
The text was updated successfully, but these errors were encountered: