658. Find K Closest Elements
Given a sorted array, two integers k
and x
, find the k
closest elements to x
in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1 Output: [1,2,3,4]
Note:
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- Absolute value of elements in the array and x will not exceed 104
class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { int n = arr.size(); if(n<k) return arr; int idx = binary_search(arr,x); cout << idx << endl; int left = max(0,idx-k); int right = min(idx+k,n-1); vector<int> res; while(left<right) { if(abs(arr[left]-x)<=abs(arr[right]-x)) right--; else left++; if((right-left+1)==k) break; } for(int i = left;i<=right;i++) res.push_back(arr[i]); return res; } private: int binary_search(vector<int>&arr,int x) { int left = 0,right=arr.size()-1; while(left<right) { int mid = (left+right)/2; if(arr[mid]==x) return mid; else if(arr[mid]>x) right = mid-1; else left = mid+1; } return left; } };