题解 | 小红的星屑共鸣
小红的星屑共鸣
https://www.nowcoder.com/practice/001cb736f02b4405819f3dad1cfc2382
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
star[] stellaris = new star[n];
while (in.hasNextLong()) {
for (int i = 0; i < n; i++) {
stellaris[i] = new star(in.nextLong(), in.nextLong());
}
}
//自定义排序规则,先按照两个星屑的x排序,再按两个星屑的y排序
Arrays.sort(stellaris, new Comparator<star>() {
@Override
public int compare(star sta, star stb) {
if(sta.x!=stb.x) {
return (int)(sta.x - stb.x);
}
return (int)(sta.y - stb.y);
}
});
//用于输出的最短距离
long minD = -1;
//最短的距离肯定存在于邻近的两个星屑间,求所有相邻的星屑间距并更新最小值即可。
for(int i = 0; i < n - 1; i++) {
long d = getD(stellaris[i],stellaris[i + 1]);
if ( minD > d || minD == -1) {
minD = d;
}
}
System.out.println(minD);
}
private static class star {
star(long x, long y) {
this.x = x;
this.y = y;
}
long x;
long y;
}
private static long getD(star sta, star stb) {
return (sta.x - stb.x) * (sta.x - stb.x) + (sta.y - stb.y) * (sta.y - stb.y);
}
}
这道题目着实困扰了我好久好久,主要是编译上的问题,自己手搓排序函数,再加上编译器老是在这个star类的构造函数上报错,但实际运行又没问题,后来看解析,没想到还有这么Arrays.sort好用的排序工具,也是看到其他大佬的解答才发现的,这道题逻辑不复杂, 排序以后最短路径只可能出现在邻近的两个星屑之间,所以只要求i和i+1之间的距离中最短的那个就行了。
