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

FIx findKthLongest For Go #1558

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

doing-cr7
Copy link

optimize code modify size to Len

`
func findKthLargest(nums []int, k int) int {
// 小顶堆,堆顶是最小元素
pq := priorityQueue{}
for _, e := range nums {
// 每个元素都要过一遍二叉堆
pq.offer(e)
// 堆中元素多于 k 个时,删除堆顶元素
if pq.Len() > 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] }

`

Fixes

我修改的是如下题目的 xx 解法:

通过截图如下:

CleanShot 2024-03-19 at 11 44 48@2x

optimize code modify size to Len
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant