Leetcode学习笔记:#973. K Closest Points to Origin
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in.)
实现:
public int[][] kClosest(int[][] points, int K){
int[][] result = new int[K][];
Arrays.sort(points, new Comparator<int[]>(){
@Override public int compare(int[] ints, int[] t1){
return (ints[0]*ints[0] + ints[1]*ints[1]) - (t1[0]*t1[0] + t1[1]*t1[1]);
}
}
for(int i = 0 ; i < K ; i ++) {
result[i] = points[i];
}
return result;
}
思路:
重新排序数组,按override的compare方法:平方和小的在前面,大的在后面,递增排序。