703. Kth Largest Element in a Stream #
Problem #
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Implement KthLargest class:
KthLargest(int k, int[] nums)Initializes the object with the integerkand the stream of integersnums.int add(int val)Returns the element representing thekthlargest element in the stream.
Example 1:
Input
["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
Output
[null, 4, 5, 5, 8, 8]
Explanation
KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3); // return 4
kthLargest.add(5); // return 5
kthLargest.add(10); // return 5
kthLargest.add(9); // return 8
kthLargest.add(4); // return 8
Constraints:
1 <= k <= 1040 <= nums.length <= 104104 <= nums[i] <= 104104 <= val <= 104- At most
104calls will be made toadd. - It is guaranteed that there will be at least
kelements in the array when you search for thekthelement.
Problem Summary #
Design a class to find the kth largest element in a data stream. Note that it is the kth largest element after sorting, not the kth distinct element. Implement the KthLargest class:
- KthLargest(int k, int[] nums) Initializes the object with the integer k and the integer stream nums.
- int add(int val) Inserts val into the data stream nums, then returns the current kth largest element in the data stream.
Solution Approach #
- After reading the problem, it is clear that this problem tests a min-heap. Build a min-heap of length K, and each time pop the heap top (the smallest element in the heap), maintaining the heap top as the Kth largest element.
- Here is a concise way to write it. Normally, to build a pq priority queue, you need to create a new type yourself and then implement the five methods Len(), Less(), Swap(), Push(), and Pop(). The sort package has a ready-made min-heap, sort.IntSlice. You can reuse it and then implement Push() and Pop() yourself to use the min-heap, saving some code.
Code #
package leetcode
import (
"container/heap"
"sort"
)
type KthLargest struct {
sort.IntSlice
k int
}
func Constructor(k int, nums []int) KthLargest {
kl := KthLargest{k: k}
for _, val := range nums {
kl.Add(val)
}
return kl
}
func (kl *KthLargest) Push(v interface{}) {
kl.IntSlice = append(kl.IntSlice, v.(int))
}
func (kl *KthLargest) Pop() interface{} {
a := kl.IntSlice
v := a[len(a)-1]
kl.IntSlice = a[:len(a)-1]
return v
}
func (kl *KthLargest) Add(val int) int {
heap.Push(kl, val)
if kl.Len() > kl.k {
heap.Pop(kl)
}
return kl.IntSlice[0]
}