-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob3.java
70 lines (56 loc) · 1.42 KB
/
prob3.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// K’th Smallest/Largest Element in Unsorted Array|Set 1
import java.util.PriorityQueue;
public class prob3 {
// Time Complexity: O(N log N)
// Auxiliary Space: O(1)
// public static int kthSmallest(Integer[] arr, int K) {
// // Sort the given array
// Arrays.sort(arr);
// // Return K'th element in
// // the sorted array
// return arr[K - 1];
// }
public static int kthSmallest(int arr[], int n, int k) {
if (k > n) {
return -1;
}
// maxHeap
PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>((n1, n2) -> n2 - n1);
for (int i = 0; i < n; i++) {
heap1.add(arr[i]);
if (heap1.size() > k) {
heap1.remove();
}
}
return heap1.peek();
}
/**
* Time Complexity: O(K + (N-K) * Log K)
* Auxiliary Space: O(K)
*
*/
public int kthLargest(int arr[], int n, int k) {
if (k > n) {
return -1;
}
// minheap
PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>((n1, n2) -> n1 - n2);
for (int i = 0; i < n; i++) {
heap1.add(arr[i]);
if (heap1.size() > k) {
heap1.remove();
}
}
return heap1.peek();
}
public static void main(String[] args) {
// Given array
int[] vec = { 2, 1, 3, 5, 4, 6 };
// Size of array
int N = vec.length;
// Given K
int K = 6;
// Function Call
System.out.println("Kth Smallest Element: " + kthSmallest(vec, N, K));
}
}