aboutsummaryrefslogtreecommitdiff
path: root/find_k_closest_elements.cpp
blob: ecc1f5320fb9f6eae435a3d173d658a2a254d6d9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "leetcode.h"

class Solution {
public:
  vector<int> findClosestElements(vector<int> &arr, int k, int x) {
    int left = 0, right = arr.size() - k;
    while (left < right) {
      int mid = (left + right) / 2;
      if (x - arr[mid] > arr[mid + k] - x)
        left = mid + 1;
      else
        right = mid;
    }
    return vector<int>(arr.begin() + left, arr.begin() + left + k);
  }
};