解题思路
手撕快排,比较符合编码规范,有良好编码风格的快排。速度快得不谈
代码
class Solution {
public int[][] kClosest(int[][] points, int k) {
quickSort(points, 0, points.length - 1, k);
return Arrays.copyOfRange(points, 0, k);
}
private void quickSort(int[][] points, int left, int right, int k) {
if (left < right) {
int pviotPosition = partition(points, left, right);
if (pviotPosition == k - 1) {
return;
} else if (pviotPosition > k - 1) {
quickSort(points, left, pviotPosition - 1, k);
} else {
quickSort(points, pviotPosition + 1, right, k);
}
}
}
private int partition(int[][] points, int left, int right) {
swap(points, left, (left + right) / 2);
int[] pviotNum = points[left];
int distance = distance(pviotNum);
while (left < right) {
while (left < right && distance(points[right]) > distance) {
right--;
}
points[left] = points[right];
while (left < right && distance(points[left]) <= distance) {
left++;
}
points[right] = points[left];
}
points[left] = pviotNum;
return left;
}
private int distance(int[] point) {
return point[0] * point[0] + point[1] * point[1];
}
private void swap(int[][] points, int a, int b) {
int[] temp = points[a];
points[a] = points[b];
points[b] = temp;
}
}