DEV Community 👩‍💻👨‍💻

Miss Pooja Anilkumar Patel
Miss Pooja Anilkumar Patel

Posted on

658. Leetcode Solution in cpp

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

Enter fullscreen mode Exit fullscreen mode

leetcode

challenge

Here is the link for the problem:
https://leetcode.com/problems/find-k-closest-elements/

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.