Leetcode

Find K Closest Elements

  • Time:O(\log(n - k) + k)
  • Space:O(k)

C++

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 {begin(arr) + l, begin(arr) + l + k};
  }
};

JAVA

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());
  }
}

Python

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]