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 −
Let us see the following implementation to get a better understanding −
#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)); }
[1,2,3,4,5] 4 3
[1,2,3,4]