The original title link is here: https://leetcode.com/problems/kth-largest-element-in-a-stream/description/
Topic:
Design a class to find the kth largest element in a stream. Note that it was the kth largest element in the sorted order and not the kth distinct element.
Your KthLargest
class'll has a constructor which accepts an integer k
and an integer array nums
, which contains initial Elements from the stream. For each call KthLargest.add
to the method, return the element representing the kth largest element in the stream.
Example:
int k = 3;int[] arr = [4,5,8,2]; Kthlargest kthlargest = new Kthlargest (3, arr); Kthlargest.add (3); Returns 4kthlargest.add (5); Returns 5kthlargest.add (10); Returns 5kthlargest.add (9); Returns 8kthlargest.add (4); Returns 8
Note:
Assume that nums
' length≥ and k-1
k
≥1.
Exercises
Maintain size with minheap in K.
Time Complexity:kthlargest, O (n * logk). Add O (LOGK). n = nums.length.
Space:o (k).
AC Java:
1 classKthlargest {2Priorityqueue<integer>minheap;3 intK;4 5 PublicKthlargest (intKint[] nums) {6 This. Minheap =NewPriorityqueue<integer>();7 This. K =K;8 for(intnum:nums) {9 Add (num);Ten } One } A - Public intAddintval) { - if(Minheap.size () <k) { the Minheap.add (val); -}Else if(Minheap.peek () <val) { - Minheap.poll (); - Minheap.add (val); + } - + returnMinheap.peek (); A } at } - - /** - * Your Kthlargest object would be instantiated and called as such: - * Kthlargest obj = new Kthlargest (k, nums); - * int param_1 = Obj.add (val); in */
Leetcode 703. Kth largest Element in a Stream