Skip to content

Commit 969e4e6

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 658_Find_K_Closest_Elements.java
1 parent 7b6f242 commit 969e4e6

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public List<Integer> findClosestElements(int[] arr, int k, int x) {
3+
int start = 0, end = arr.length - 1 - k;
4+
5+
while (start <= end) {
6+
int mid = start + (end - start) / 2;
7+
8+
if (Math.abs(x - arr[mid]) > Math.abs(x - arr[mid + k])) {
9+
start = mid + 1;
10+
} else {
11+
end = mid - 1;
12+
}
13+
}
14+
15+
List<Integer> result = new ArrayList<>();
16+
for (int i = start; i < start + k; i++) {
17+
result.add(arr[i]);
18+
}
19+
20+
return result;
21+
}
22+
}

0 commit comments

Comments
 (0)