题目
给定一些 points 和一个 origin,从 points 中找到 k 个离 origin 最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。
样例
给出
points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 3
返回 [[1,1],[2,5],[4,4]]
代码
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
public static void main(String[] args) {
int k = 3;
Point[] result = new Point[k];
Point origin = new Point(0, 0);
Point[] points = {
new Point(4, 6),
new Point(4, 7),
new Point(4, 4),
new Point(2, 5),
new Point(1, 1)
};
result = kClosest(points, origin, k);
for (Point p : result) {
System.out.println("[" + p.x + "," + p.y + "]");
}
}
public Point[] kClosest(Point[] points, Point origin, int k) {
Point[] result = new Point[k];
Point tmpPoint = new Point();
for (int i = 0; i < points.length; i++) {
for (int j = i; j < points.length; j++) {
//比较点和origin点的距离,若前面的点的距离大于后面点的距离,则交换两个点的位置
if (calcLength(points[i], origin) > calcLength(points[j],
origin)) {
tmpPoint = points[i];
points[i] = points[j];
points[j] = tmpPoint;
}//如果两个点有相同距离,则按照x值来排序
else if (calcLength(points[i], origin) == calcLength(
points[j], origin)) {
if (points[i].x > points[j].x) {
tmpPoint = points[i];
points[i] = points[j];
points[j] = tmpPoint;
}//若x值相同,按照y值排序。
else if (points[i].x == points[j].x) {
if (points[i].y == points[j].y) {
tmpPoint = points[i];
points[i] = points[j];
points[j] = tmpPoint;
}
}
}
}
}
//输出符合条件的前k的点
for (int i = 0; i < k; i++) {
result[i] = points[i];
}
return result;
}
//计算两点间距离
public static double calcLength(Point point, Point origin) {
double length = Math.sqrt((point.x - origin.x) * (point.x - origin.x)
+ (point.y - origin.y) * (point.y - origin.y));
return length;
}
}