Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bug][Go] find-Kth-Largest #1557

Open
2 tasks done
doing-cr7 opened this issue Mar 19, 2024 · 0 comments
Open
2 tasks done

[bug][Go] find-Kth-Largest #1557

doing-cr7 opened this issue Mar 19, 2024 · 0 comments
Labels
help wanted Extra attention is needed

Comments

@doing-cr7
Copy link

请在提交 bug 之前先搜索

  • 我已经搜索过 issues,没有发现相同的 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?

  • 我愿意!
@doing-cr7 doing-cr7 added the help wanted Extra attention is needed label Mar 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant