Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int helper(int left, int right, const vector<int>& arr, int x)
- {
- if (x < arr[0]) return 0;
- if (x > arr[arr.size() - 1]) return arr.size() - 1;
- int mid = left + (right - left) / 2;
- if (arr[mid] == x)
- {
- return mid;
- }
- else if (arr[mid] > x)
- {
- if (mid - 1 >= 0 && arr[mid - 1] < x)
- {
- return abs(x - arr[mid - 1]) < abs(x - arr[mid]) ? mid - 1 : mid;
- }
- return helper(left, mid - 1, arr, x);
- }
- else
- {
- if (mid + 1 < arr.size() && arr[mid + 1] > x)
- {
- return abs(x - arr[mid + 1]) < abs(x - arr[mid]) ? mid + 1: mid;
- }
- return helper(mid + 1, right, arr, x);
- }
- }
- vector<int> findClosestElements(vector<int>& arr, int k, int x) {
- int pos = helper(0, arr.size(), arr, x);
- vector<int> result;
- result.reserve(k);
- int i = pos;
- int j = pos + 1;
- while (result.size() < k)
- {
- if (i >=0 && j <arr.size())
- {
- if (abs(x - arr[i]) <= abs(x - arr[j]))
- {
- result.push_back(arr[i]);
- i--;
- }
- else
- {
- result.push_back(arr[j]);
- j++;
- }
- }
- else if (i >= 0)
- {
- result.push_back(arr[i]);
- i--;
- }
- else
- {
- result.push_back(arr[j]);
- j++;
- }
- }
- // todo is should be more efficient somehow
- sort(result.begin(), result.end());
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement