Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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 解法:
通过截图如下: