forked from Teju-1212/hacktoberfest-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthmaximum.java
More file actions
36 lines (28 loc) · 970 Bytes
/
kthmaximum.java
File metadata and controls
36 lines (28 loc) · 970 Bytes
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
import java.util.Collections;
import java.util.PriorityQueue;
public class findkthsmallesteleminmatrix {
public static void kthsmallestmatrixelement(int[][] arr, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
System.out.println(arr.length);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (pq.size() < k) {
pq.add(arr[i][j]);
}
else if (pq.peek() > arr[i][j]) {
pq.poll();
pq.add(arr[i][j]);
}
}
}
System.out.println(k + "th smallest element in the array: " + pq.peek());
}
public static void main(String[] args) {
int[][] arr = {
{ 1, 5, 9 },
{ 10, 11, 13 },
{ 12, 13, 15 }
};
kthsmallestmatrixelement(arr, 8);
}
}