Skip to content

Commit 7944156

Browse files
authored
Biased Binary Search; Arrays.stream(int[]).boxed().collect(Collectors.toList()) to convert array to list
1 parent a94eb5e commit 7944156

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Find K Closest Elements.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
class Solution {
2+
public List<Integer> findClosestElements(int[] arr, int k, int x) {
3+
if(k > arr.length) return null;
4+
int n = arr.length;
5+
int lo = 0, hi = n - k;
6+
7+
// binary search find the left starting point
8+
while(lo < hi) {
9+
int m = lo + (hi - lo) / 2;
10+
if(x - arr[m] > arr[m+k] - x) lo = m + 1;
11+
else hi = m;
12+
}
13+
int[] res = Arrays.copyOfRange(arr, lo, lo + k);
14+
return Arrays.stream(res).boxed().collect(Collectors.toList());
15+
}
16+
}

0 commit comments

Comments
 (0)