forked from MAYANK25402/Hacktober-Fest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargestElementInAStream.java
More file actions
84 lines (71 loc) · 1.88 KB
/
KthLargestElementInAStream.java
File metadata and controls
84 lines (71 loc) · 1.88 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Scanner;
class MinHeap
{
final PriorityQueue<Integer> pq;
final int k;
public MinHeap(int k)
{
this.k = k;
pq = new PriorityQueue<>(k);
}
public int add(int n)
{
// if the min-heap's size is less than `k`, push the current element
// into the min-heap
if (pq.size() < k) {
pq.add(n);
}
// otherwise, if the current element is more than the smallest element
// in the min-heap, remove the smallest element from the heap and
// push the current element
else if (pq.peek() < n)
{
pq.poll();
pq.add(n);
}
// if the size of the min-heap reaches `k`, return the top element
if (pq.size() == k) {
return pq.peek();
}
else {
return -1;
}
}
}
class Solution
{
public static MinHeap pq = null;
// Function to find the k'th largest element in a stream
public static int findKthLargest(int k, int nextInt)
{
// create MinHeap class instance first time when function is invoked
if (pq == null) {
pq = new MinHeap(k);
}
return pq.add(nextInt);
}
}
class Main
{
public static void main(String[] args)
{
int k = 3;
Scanner in = new Scanner(System.in);
// loop till the end-of-file (EOF) is reached
while (true)
{
try {
int nextInt = in.nextInt();
int x = Solution.findKthLargest(k, nextInt);
if (x != -1) {
System.out.println("The k'th largest element is " + x);
}
} catch (NoSuchElementException e) {
break;
}
}
in.close();
}
}