Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> findClosestElements(vector<int>& arr, int k, int x) {
- int left=0, right=arr.size()-k;
- // Binary search the first val in range [0, n-k].
- // Decide where to move the sliding window based on 4 conditions.
- // Here leftmost bs is used since we want the leftmost starting point satisfying all conditions.
- while(left<right){
- int mid = (left+right)/2;
- if(x-arr[mid] > arr[mid+k]-x)
- left = mid+1;
- else
- right = mid;
- }
- // Get the elements of sliding window in vector and return.
- vector<int> ans;
- for(int i=left; i<left+k; i++)
- ans.push_back(arr[i]);
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement