forked from Anuj-Kumar-Sharma/Java-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainClass.java
More file actions
71 lines (57 loc) · 1.37 KB
/
Copy pathMainClass.java
File metadata and controls
71 lines (57 loc) · 1.37 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
package priorityQueue1;
import java.util.*;
public class MainClass {
static int findKthSmallest(int a[], int k) {
if(k > a.length) return -1;
Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i = 0; i<k; i++) {
pq.offer(a[i]);
}
for(int i = k; i<a.length; i++) {
System.out.println(pq);
if(pq.peek() > a[i]) {
pq.poll();
pq.offer(a[i]);
}
}
System.out.println(pq);
return pq.peek();
}
static int findKthLargest(int a[], int k) {
if(k > a.length) return -1;
Queue<Integer> pq = new PriorityQueue<>();
for(int i = 0; i<k; i++) {
pq.offer(a[i]);
}
for(int i = k; i<a.length; i++) {
System.out.println(pq);
if(pq.peek() < a[i]) {
pq.poll();
pq.offer(a[i]);
}
}
System.out.println(pq);
return pq.peek();
}
public static void main(String[] args) {
int a[] = {1, 4, 9, 2, 5, 6, 7};
int k = 3;
System.out.println(findKthLargest(a, k));
// Queue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
//
// pq.offer(5);
// pq.offer(10);
// pq.offer(9);
// pq.offer(1);
//
// System.out.println(pq);
// System.out.println(pq.poll());
// System.out.println(pq);
// System.out.println(pq.poll());
// System.out.println(pq);
// System.out.println(pq.poll());
// System.out.println(pq);
// System.out.println(pq.poll());
// System.out.println(pq);
}
}