-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathKClosestElement.java
59 lines (52 loc) · 1.48 KB
/
KClosestElement.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
package SummerTrainingGFG.Heap;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author Vishal Singh
* 16-01-2021
*/
public class KClosestElement {
static class Pair {
int elem;
int diff;
Pair(int elem, int diff) {
this.elem = elem;
this.diff = diff;
}
}
static class SortByDiff implements Comparator<Pair> {
public int compare(Pair a, Pair b) {
return b.diff - a.diff;
}
}
public static void getKClosestElement(int[] arr, int n, int k, int x) {
PriorityQueue<Pair> pq = new PriorityQueue<>(new SortByDiff());
/*
* I will do it today but in morning
* */
for (int i = 0; i < k; i++) {
pq.add(new Pair(
arr[i],
Math.abs(arr[i] - x)
));
}
for (int i = k; i < n; i++) {
Pair curr = pq.peek();
if (curr != null && curr.diff > Math.abs(arr[i] - x)) {
pq.poll();
pq.add(new Pair(arr[i], Math.abs(arr[i] - x)));
}
}
System.out.print("K closest elements are: ");
for (Pair p : pq) {
System.out.print(" { "+p.elem + " } ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {10, 15, 7, 3, 4};
int k = 3;
int closestTo = 8;
getKClosestElement(arr, arr.length, k, closestTo);
}
}