https://leetcode.com/problems/kth-largest-element-in-a-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
SC = O(k)
TC = O (log k) as we are storing only k elements, and up heapify will take only O(log k)
package pep.Day66;
import java.util.PriorityQueue;
import java.util.Queue;
public class LeetCode_703_Kth_Largest_Element_in_Stream {
public static void main(String[] args) {
int[] arr = {4, 5, 8, 2};
int k = 3;
KthLargest kl = new KthLargest(k, arr);
System.out.println(kl.add(3));
System.out.println(kl.add(5));
System.out.println(kl.add(10));
System.out.println(kl.add(9));
System.out.println(kl.add(4));
}
static class KthLargest {
Queue<Integer> pq;
int K;
public KthLargest(int k, int[] nums) {
K = k;
pq = new PriorityQueue<>();
for (int i : nums) {
pq.add(i);
if (pq.size() > k)
pq.remove();
}
}
public int add(int val) {
pq.add(val);
if (pq.size() > K)
pq.remove();
return pq.peek();
}
}
}
No comments:
Post a Comment