Skip to content

Commit 6166683

Browse files
committed
Create 0658-find-k-closest-elements.java
1 parent 1c4fd3e commit 6166683

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public List<Integer> findClosestElements(int[] arr, int k, int x) {
3+
int l =0;
4+
int r = arr.length -k;
5+
List<Integer> result = new ArrayList<>();
6+
while( l < r){
7+
int m = (l+r) /2;
8+
if(x - arr[m] > arr[m+k] -x ){ //right is closer
9+
l = m+1;
10+
}else{ //left is closer
11+
r =m;
12+
}
13+
}
14+
for(int i =l; i < l+k; i++){ //build the solution list
15+
result.add(arr[i]);
16+
}
17+
return result;
18+
}
19+
}

0 commit comments

Comments
 (0)