2.Kth Largest Element in a Stream
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.
Your KthLargest
class will have a constructor which accepts an integer k
and an integer array nums
, which contains initial elements from the stream. For each call to the method KthLargest.add
, return the element representing the kth largest element in the stream.
Example:
Solution I: (Using a sorted array of size K)
Time Complexity: Insertion of new element : O(K) Finding the K largest will take O(1) Algo: If the new element is smaller ignore it. Else add in correct position by searching.
Solution II: (Using Min Heap)
Last updated