Find K Closest Elements in C++


Suppose we have a sorted array, two integers k and x are also given, we have to find the k closest elements to x in that array. The result should be sorted in increasing order. If there is a tie, the smaller elements are always preferred. So if the input is like [1,2,3,4,5] and k = 4, x = 3, then output will be [1,2,3,4]

To solve this, we will follow these steps −

  • Make an array called ans
  • set low := 0, high := size of the array – k
  • while low < high
    • mid := low + (high - low) /2
    • if x – arr[mid] > arr[mid + k] – x, then low := mid + 1, otherwise high := mid
  • for i in range low to low + k
    • insert arr[i] into ans array
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
cout << "]"<<endl;
}
class Solution {
public:
   vector<int> findClosestElements(vector<int>& arr, int k, int x) {
      vector <int> ans;
      int low = 0;
      int high = arr.size() - k;
      while(low < high){
         int mid = low + (high - low)/2;
         if(x - arr[mid] > arr[mid + k] - x){
            low = mid + 1;
         }
         else high = mid;
      }
      for(int i = low ; i < low + k ; i++)ans.push_back(arr[i]);
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,3,4,5};
   print_vector(ob.findClosestElements(v, 4, 3));
}

Input

[1,2,3,4,5]
4
3

Output

[1,2,3,4]

Updated on: 29-Apr-2020

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements