Skip to content

Commit 451713f

Browse files
committed
堆: top k
Change-Id: If00c7e780ccbfdd21db98464e6910a39a8625fb0
1 parent 1e368e7 commit 451713f

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Diff for: go/leetcode/215.数组中的第k个最大元素.go

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*
2+
* @lc app=leetcode.cn id=215 lang=golang
3+
*
4+
* [215] 数组中的第K个最大元素
5+
*
6+
* https://leetcode-cn.com/problems/kth-largest-element-in-an-array/description/
7+
*
8+
* algorithms
9+
* Medium (59.34%)
10+
* Likes: 293
11+
* Dislikes: 0
12+
* Total Accepted: 58.7K
13+
* Total Submissions: 98.9K
14+
* Testcase Example: '[3,2,1,5,6,4]\n2'
15+
*
16+
* 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
17+
*
18+
* 示例 1:
19+
*
20+
* 输入: [3,2,1,5,6,4] 和 k = 2
21+
* 输出: 5
22+
*
23+
*
24+
* 示例 2:
25+
*
26+
* 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
27+
* 输出: 4
28+
*
29+
* 说明:
30+
*
31+
* 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
32+
*
33+
*/
34+
35+
// top k,第一反应用堆,构造一个大小为k的最小堆,判断堆顶元素
36+
// package leetcode
37+
38+
// @lc code=start
39+
import (
40+
"container/heap"
41+
)
42+
43+
type myHeap []int
44+
45+
func (h *myHeap) Less(i, j int) bool {
46+
return (*h)[i] < (*h)[j]
47+
}
48+
49+
func (h *myHeap) Swap(i, j int) {
50+
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
51+
}
52+
53+
func (h *myHeap) Len() int {
54+
return len(*h)
55+
}
56+
57+
func (h *myHeap) Pop() (v interface{}) {
58+
*h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1]
59+
return
60+
}
61+
62+
func (h *myHeap) Push(v interface{}) {
63+
*h = append(*h, v.(int))
64+
}
65+
66+
func findKthLargest(nums []int, k int) int {
67+
h := make(myHeap, 0)
68+
heap.Init(&h)
69+
for _, cur := range nums {
70+
if h.Len() >= k {
71+
if cur <= h[0] {
72+
continue
73+
}
74+
heap.Pop(&h)
75+
}
76+
heap.Push(&h, cur)
77+
}
78+
return h[0]
79+
}
80+
81+
// @lc code=end

0 commit comments

Comments
 (0)