Binary Search and Two Pointers  - 18 ms
Noticing the array is sorted, so we can using binary search to get a rough area of target numbers, and then expand it to the left k-1 more and right k-1 more el
Noticing the array is sorted, so we can using binary search to get a rough area of target numbers, and then expand it to the left k-1 more and right k-1 more elements, then searching from the left to right. If the left element is more close or equal to the target number x than the right element, then move the right index to the left one step. Otherwise, move the left index to right one step. Once, the element between the left and right is k, then return the result.\n\n**Java**\n```java\npublic class Solution {\n\tpublic List<Integer> findClosestElements(List<Integer> arr, int k, int x) {\n\t\tint index = Collections.binarySearch(arr, x);\n\t\tif (index == -1)\n\t\t\treturn arr.subList(0, k);\n\t\telse if (index >= arr.size())\n\t\t\treturn arr.subList(arr.size() - k, arr.size());\n\t\telse {\n\t\t\tif (index < 0)\n\t\t\t\tindex = -index - 1;\n\t\t\tint left = Math.max(0, index - k - 1), right = Math.min(arr.size() - 1, index + k - 1);\n\n\t\t\twhile (right - left > k - 1) {\n\t\t\t\tif (left < 0 || (x - arr.get(left)) <= (arr.get(right) - x))\n\t\t\t\t\tright--;\n\t\t\t\telse if (right > arr.size() - 1 || (x - arr.get(left)) > (arr.get(right) - x))\n\t\t\t\t\tleft++;\n\t\t\t\telse\n\t\t\t\t\tSystem.out.println("unhandled case: " + left + " " + right);\n\t\t\t}\n\n\t\t\treturn arr.subList(left, right + 1);\n\t\t}\n\t}\n}\n```\nHere is an updated version.\n```java\npublic class Solution {\n\tpublic List<Integer> findClosestElements(List<Integer> arr, int k, int x) {\n\t\tint n = arr.size();\n\t\tif (x <= arr.get(0)) {\n\t\t\treturn arr.subList(0, k);\n\t\t} else if (arr.get(n - 1) <= x) {\n\t\t\treturn arr.subList(n - k, n);\n\t\t} else {\n\t\t\tint index = Collections.binarySearch(arr, x);\n\t\t\tif (index < 0)\n\t\t\t\tindex = -index - 1;\n\t\t\tint low = Math.max(0, index - k - 1), high = Math.min(arr.size() - 1, index + k - 1);\n\n\t\t\twhile (high - low > k - 1) {\n\t\t\t\tif (low < 0 || (x - arr.get(low)) <= (arr.get(high) - x))\n\t\t\t\t\thigh--;\n\t\t\t\telse if (high > arr.size() - 1 || (x - arr.get(low)) > (arr.get(high) - x))\n\t\t\t\t\tlow++;\n\t\t\t\telse\n\t\t\t\t\tSystem.out.println("unhandled case: " + low + " " + high);\n\t\t\t}\n\t\t\treturn arr.subList(low, high + 1);\n\t\t}\n\t}\n}\n```
['Two Pointers', 'Java']