和苏微二面的题有点像,也是按照一个不常规的值来给一组元素做快速排序,找到pivot位置为指定的k时
这道题更简单,不需要构造多个容器
/**
* 对points快速排序,按照每个point(x, y)的 x^2 + y^2的大小
* 找到pivotIdx == k的地方,左边的所有点就是答案
* Runtime: 8 ms, faster than 86.92%
* Memory Usage: 47.5 MB, less than 72.21%
*/
class Solution {
public int[][] kClosest(int[][] points, int k) {
// quick sort
int left = 0, right = points.length - 1;
while (left < right) {
int start = left, end = right, mid = (start + end) / 2;
int[] pivot = points[mid];
double pivotVal = Math.pow(pivot[0], 2) + Math.pow(pivot[1], 2);
points[mid] = points[right];
while (start < end) {
while (start < end && Math.pow(points[start][0], 2) + Math.pow(points[start][1], 2) <= pivotVal) {
start++;
}
points[end] = points[start];
while (start < end && Math.pow(points[end][0], 2) + Math.pow(points[end][1], 2) >= pivotVal) {
end--;
}
points[start] = points[end];
}
points[start] = pivot;
if (start == k) {
break;
}
if (start > k) {
right = start - 1;
} else {
left = start + 1;
}
}
int[][] res = new int[k][2];
for (int i = 0; i < k; i++) { // can be replaced with "System.arraycopy(points, 0, res, 0, k);" (submitted and got the same time and space comsumption)
res[i] = points[i];
}
return res;
}
}

本文介绍了一种使用快速排序算法寻找二维平面上k个离原点最近的点的方法。通过计算每个点到原点的距离平方并以此作为排序依据,利用快速排序算法特性找到第k个最近的点作为轴点,实现高效查找。
3218

被折叠的 条评论
为什么被折叠?



