Leetcode 658 Find K Closest Elements
Description
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
题意分析
题目的意思就是给出一个数组(vector)arr,和数字k、x,在数组arr里面找出k个与x最相近的数字,当数字两边对称的时候(大致这样称呼),取小的数。比如说x=5,有4、6可取的时候就取4。
一开始我的解法就是先找出那个不大于x的数字的下标,然后从这个下标开始,向两边和x作比较然后不断增大res(结果)的大小,最后返回结果。比较直观容易理解,但是耗时较多:
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
vector<int> res;
int size = arr.size();
if (x <= arr[0]) {
for (int i = 0; i < k; i++)
res.push_back(arr[i]);
} else if (x >= arr[size - 1]) {
int t = size - 1;
for (int i = 0; i < k; i++)
res.push_back(arr[t--]);
} else {
int pos = -1;
for (int i = 0; i < size - 1; i++)
if (arr[i] > x && pos == -1)
pos = i - 1;
int left = pos - 1, right = pos + 1, leftD, rightD;
res.push_back(arr[pos]);
while (res.size() < k) {
if (left >= 0)
leftD = abs(x - arr[left]);
else
leftD = INT_MAX;
// res.push_back(arr[left--]);
if (right < size)
rightD = abs(x - arr[right]);
else
rightD = INT_MAX;
// 如果左边差值大,就应该使用右边的值
if (leftD > rightD)
res.push_back(arr[right++]);
else
res.push_back(arr[left--]);
}
}
for (int i = 0; i < k; i++)
cout << res[i] << '\t';
sort(res.begin(), res.end());
return res;
}
};
这个版本好像是149ms,后来看了下别人的答案,发现时类似的,但是很多地方可以优化,比如说找出下标那里可以用二分法查找,后面返回结果可以直接就输出整个初始化的vector,最后得到优化版的答案如下:
bool myfunction (int i,int j) { return (i<j); }
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int l = 0, r = arr.size() - 1, mid, pos = -1;
while (l < r) {
mid = l + (r - l) / 2;
if (arr[mid] == x) {
pos = mid;
break;
} else if (arr[mid] < x) {
l = mid + 1;
} else {
r = mid - 1;
}
}
// pos为第一个不大于x的数字下标
if (pos == -1) {
if (l == 0)
pos = 0;
else if (abs(x - arr[l]) > abs(x - arr[l - 1]))
pos = l - 1;
else
pos = l;
}
// mid用来计数
mid = 0;
l = pos - 1, r = pos;
cout << pos << endl;
while (mid < k) {
//要同时判断r的大小,不然的话r超出数组的范围继续计数出现错误,这里leetcode不会直接提示
if (l < 0 || (r < arr.size() && abs(arr[l] - x) > abs(arr[r] - x)))
r++;
else
l--;
mid++;
}
cout << l << '\t' << r << endl;
return vector<int>(arr.begin() + l + 1, arr.begin() + r);
}
};
最后一个版本的耗时是113ms,比较理想。