Skip to content

Commit 8a6c747

Browse files
authored
Create Solution2.go
1 parent 9c2a25c commit 8a6c747

File tree

1 file changed

+21
-0
lines changed
  • solution/0200-0299/0215.Kth Largest Element in an Array

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
func findKthLargest(nums []int, k int) int {
2+
minQ := hp{}
3+
for _, x := range nums {
4+
heap.Push(&minQ, x)
5+
if minQ.Len() > k {
6+
heap.Pop(&minQ)
7+
}
8+
}
9+
return minQ.IntSlice[0]
10+
}
11+
12+
type hp struct{ sort.IntSlice }
13+
14+
func (h hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
15+
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
16+
func (h *hp) Pop() any {
17+
a := h.IntSlice
18+
v := a[len(a)-1]
19+
h.IntSlice = a[:len(a)-1]
20+
return v
21+
}

0 commit comments

Comments
 (0)