Find K Closest Elements LeetCode solution in Java

1
class Solution {
2
public List<Integer> findClosestElements(int[] arr, int k, int x) {
3
List<Integer> result = new ArrayList<>();
4

5
int low = 0, high = arr.length - 1;
6

7
while (high - low >= k) {
8
if (Math.abs(arr[low] - x) > Math.abs(arr[high] - x)) low++;
9
else high--;
10
}
11

12
for (int i = low; i <= high; i++) result.add(arr[i]);
13

14
return result;
15
}
16
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0