Skip to content

658. Find K Closest Elements 👍

  • Time: $O(\log(n - k) + k)$
  • Space: $O(k)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<int> findClosestElements(vector<int>& arr, int k, int x) {
    int l = 0;
    int r = arr.size() - k;

    while (l < r) {
      const int m = (l + r) / 2;
      if (x - arr[m] <= arr[m + k] - x)
        r = m;
      else
        l = m + 1;
    }

    return {arr.begin() + l, arr.begin() + l + k};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public List<Integer> findClosestElements(int[] arr, int k, int x) {
    int l = 0;
    int r = arr.length - k;

    while (l < r) {
      final int m = (l + r) / 2;
      if (x - arr[m] <= arr[m + k] - x)
        r = m;
      else
        l = m + 1;
    }

    return Arrays.stream(arr, l, l + k).boxed().collect(Collectors.toList());
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def findClosestElements(self, arr: list[int], k: int, x: int) -> list[int]:
    l = 0
    r = len(arr) - k

    while l < r:
      m = (l + r) // 2
      if x - arr[m] <= arr[m + k] - x:
        r = m
      else:
        l = m + 1

    return arr[l:l + k]