[LeetCode]447 Number of Boomerangs

Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between iand j equals the distance between i and k (the order of the tuple matters).

Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000](inclusive).

Example:

Input:
[[0,0],[1,0],[2,0]]

Output:
2

Explanation:
The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]


解法:
双重循环,记录每个点和其他的点的距离。
复制代码
public int numberOfBoomerangs(int[][] points) {
        int result = 0;
        for(int i = 0; i< points.length; i++){
            Map<Integer,Integer> hash = new HashMap<>();
            for( int j = 0; j< points.length; j++){
                if(i == j){
                    continue;
                }else{
                    int dist = getDistance(points[i],points[j]);
                    hash.put(dist,hash.getOrDefault(dist,0)+1);
                }
            }
            for(Integer val : hash.values()){
                result += val * (val - 1);
            }
        }
        return result;
    }

    int getDistance(int[] p1, int[] p2){
        int x = p1[0] - p2[0];
        int y = p1[1] - p2[1];
        return x*x + y*y;
    }
复制代码

 

posted @   JavaNerd  阅读(975)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示