Skip to content

Commit 7182078

Browse files
Merge pull request #1854 from AP-Repositories/patch-2
Create 0703-kth-largest-element-in-a-stream.go
2 parents ede62e6 + de553f7 commit 7182078

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
type IntHeap []int
2+
3+
func (h IntHeap) Len() int { return len(h) }
4+
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
5+
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
6+
func (h *IntHeap) Push(x interface{}) {*h = append(*h, x.(int))}
7+
func (h *IntHeap) Pop() interface{} {
8+
old := *h
9+
n := len(old)
10+
x := old[n-1]
11+
*h = old[0 : n-1]
12+
return x
13+
}
14+
15+
type KthLargest struct {
16+
minHeap *IntHeap
17+
k int
18+
}
19+
20+
21+
func Constructor(k int, nums []int) KthLargest {
22+
tmp := IntHeap(nums)
23+
this := KthLargest{minHeap: &tmp, k: k}
24+
heap.Init(this.minHeap)
25+
for len(*this.minHeap) > k {
26+
heap.Pop(this.minHeap)
27+
}
28+
return this
29+
}
30+
31+
32+
func (this *KthLargest) Add(val int) int {
33+
heap.Push(this.minHeap, val)
34+
if len(*this.minHeap) > this.k {
35+
heap.Pop(this.minHeap)
36+
}
37+
return (*this.minHeap)[0]
38+
}

0 commit comments

Comments
 (0)