Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1854 from AP-Repositories/patch-2
Browse files Browse the repository at this point in the history
Create 0703-kth-largest-element-in-a-stream.go
  • Loading branch information
AP-Repositories authored Jan 3, 2023
2 parents ede62e6 + de553f7 commit 7182078
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions go/0703-kth-largest-element-in-a-stream.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
type IntHeap []int

func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {*h = append(*h, x.(int))}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}

type KthLargest struct {
minHeap *IntHeap
k int
}


func Constructor(k int, nums []int) KthLargest {
tmp := IntHeap(nums)
this := KthLargest{minHeap: &tmp, k: k}
heap.Init(this.minHeap)
for len(*this.minHeap) > k {
heap.Pop(this.minHeap)
}
return this
}


func (this *KthLargest) Add(val int) int {
heap.Push(this.minHeap, val)
if len(*this.minHeap) > this.k {
heap.Pop(this.minHeap)
}
return (*this.minHeap)[0]
}

0 comments on commit 7182078

Please sign in to comment.