-
Notifications
You must be signed in to change notification settings - Fork 16
/
FindKClosestElements.java
41 lines (36 loc) · 1.28 KB
/
FindKClosestElements.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
// https://leetcode.com/problems/find-k-closest-elements
// T: O(logN + KLogK)
// S: O(logK)
import java.util.ArrayList;
import java.util.List;
public class FindKClosestElements {
public static List<Integer> findClosestElements(int[] array, int k, int x) {
final int index = binarySearch(array, x);
final List<Integer> result = new ArrayList<>();
for (int left = index - 1, right = index ; k > 0 ; k--) {
if (left == -1) {
result.add(array[right++]);
} else if (right == array.length) {
result.add(array[left--]);
} else {
if (Math.abs(array[left] - x) <= Math.abs(array[right] - x)) {
result.add(array[left--]);
} else {
result.add(array[right++]);
}
}
}
result.sort(Integer::compareTo);
return result;
}
private static int binarySearch(int[] array, int x) {
int left = 0, right = array.length - 1, middle;
while (left <= right) {
middle = left + (right - left) / 2;
if (array[middle] == x) return middle;
else if (array[middle] < x) left = middle + 1;
else right = middle - 1;
}
return left;
}
}