# 658. Find K Closest Elements

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mjm0_TrGbTTqwsWF_sz%2F-MjnqR7W_LrBwi9oTJN4%2Fimage.png?alt=media\&token=04d07ce8-b033-4e71-b8cc-cbf912662627)

**Binary Search + Sliding Window**

**time: O(logn+k)**

**space: O(1)**

```java
class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> res = new ArrayList<>();
        int left = 0;
        int right = arr.length - k;
        
        while (left < right) {
            int mid = left + (right - left)/2;
            if (x - arr[mid] > arr[mid+k] - x) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        
        for (int i = left; i < left + k; i++) {
            res.add(arr[i]);
        }
        return res;
    }
}
```
