closest element K | c++
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
vector<int> arrOut;
vector <int> :: iterator iterPrev, iterNext;
iterPrev = find(arr.begin(), arr.end(), x);
if (*iterPrev == x)
{
arrOut.push_back(*iterPrev);
iterNext = iterPrev;
iterNext++;
iterPrev--;
for(k; k>1; k--){
if(iterNext > arr.end() || iterPrev < arr.begin()){
arrOut.push_back(*iterPrev);
iterPrev--;
}
else if(iterPrev > arr.end() || iterPrev < arr.begin()){
arrOut.push_back(*iterNext);
iterNext++;
}
else if( (x-*iterPrev) < (*iterNext-x) ){
arrOut.push_back(*iterPrev);
iterPrev--;
}
else if( (x-*iterPrev) > (*iterNext-x) ){
arrOut.push_back(*iterNext);
iterNext++;
}
else if( (x-*iterPrev) == (*iterNext-x) ){
if(*iterPrev<*iterNext){
arrOut.push_back(*iterPrev);
iterPrev--;
}
else {
arrOut.push_back(*iterNext);
iterNext++;
}
}
}
}
else {
iterPrev = arr.begin();
iterNext = arr.end()-1;
for(k; k>=1; k--){
if( arr.back() < x ){
arrOut.push_back(*iterNext);
iterNext--;
}
if(arr.front() > x ){
arrOut.push_back(*iterPrev);
iterPrev++;
}
}
}
sort(arrOut.begin(), arrOut.end());
return arrOut;
}
};
Comments
Post a Comment