题解 | 小红的星屑共鸣

小红的星屑共鸣

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之间的距离中最短的那个就行了。

全部评论
这个答案不对,“最短的距离肯定存在于邻近的两个星屑间”,这句不成立,影响距离的不止x,还有y,还有角度。 比如这个输入用例: 3 0 0 1 9 2 1 输出是65,而期望是 5
点赞 回复 分享
发布于 03-09 11:33 四川

相关推荐

点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务