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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { int xIndex = searchNearestIndex(arr, x); int startIndex = xIndex, endIndex = xIndex; k--; while (k > 0) { if (startIndex - 1 < 0) { endIndex++; } else if (endIndex + 1 >= arr.length) { startIndex--; } else { if (x - arr[startIndex - 1] <= arr[endIndex + 1] - x) { startIndex--; } else { endIndex++; } } k--; }
List<Integer> numList = new ArrayList<>(endIndex - startIndex + 1); for (int i = startIndex; i <= endIndex; i++) { numList.add(arr[i]); } return numList; }
private int searchNearestIndex(int[] arr, int x) { int i = 0, j = arr.length - 1; while (i < j) { int mid = (i + j) >>> 1; if (arr[mid] < x) { i = mid + 1; } else if (arr[mid] > x) { j = mid; } else { return mid; } }
if (j == 0) { return 0; } else { i = j - 1; if (Math.abs(arr[i] - x) <= Math.abs(arr[j] - x)) { return i; } else { return j; } } } }
|
References
658. Find K Closest Elements