-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkth_minimum_element_in_stream.java
54 lines (49 loc) · 1.26 KB
/
kth_minimum_element_in_stream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Comparator;
public class kth_minimum_element_in_stream {
public static void main(String[] args) {
int arr[]={3,1,5,89,0,-1,23,2,6,-5};
int k=3;
Comparator<Integer> c = new Comparator<Integer>()
{
@Override
public int compare(Integer a,Integer b)
{
return b-a;
}
};
PriorityQueue<Integer> queue= new PriorityQueue<Integer>(c); //comparator object is used for max heap creation
for(int i=0;i<arr.length;i++)
{
if(i+1<k)
{
queue.add(arr[i]);
System.out.print(-1+" ");
}
else
{
if(i+1==k)
{
queue.add(arr[i]);
System.out.print(queue.peek()+" ");
}
else if(queue.peek()<arr[i])
{
System.out.print(queue.peek()+" ");
}
else
{
queue.poll();
queue.add(arr[i]);
System.out.print(queue.peek()+" ");
}
}
}
}
}
/*
OUTPUT
run:
-1 -1 5 5 3 1 1 1 1 0 BUILD SUCCESSFUL (total time: 0 seconds)
*/