class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { //查找,二分法找到那个数的lowerbound然后左右指针比较;O(logn+2k) vector<int>::iterator p=lower_bound(arr.begin(),arr.end(),x); if(p!=arr.begin() && *p != x) p--; vector<int> res; int len=arr.size(); int l=p-arr.begin(),r=p-arr.begin(); //cout<<l<<","<<r<<endl; while(r-l<k-1){ if(l==0){ r++;continue; } if(r==len-1){ l--;continue; } if(arr[r+1]-x>=x-arr[l-1]) l--; else r++; } for(int i=l;i<=r;i++) res.push_back(arr[i]); return res; } };