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 i
and 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]]
题目含义:定义一种类似“回形标”的三元组结构,即在三元组(i, j, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。
1 private int getDistance(int[] p1, int[] p2) { 2 int x = p1[0] - p2[0]; 3 int y = p1[1] - p2[1]; 4 return x * x + y * y; 5 } 6 7 public int numberOfBoomerangs(int[][] points) { 8 if (points.length == 0 || points[0].length == 0) return 0; 9 int result = 0; 10 for (int i = 0; i < points.length; i++) { 11 Map<Integer, Integer> distances = new HashMap<>(); 12 for (int j = 0; j < points.length; j++) { 13 if (i == j) continue; 14 int distance = getDistance(points[i], points[j]); 15 distances.put(distance, distances.getOrDefault(distance, 0) + 1); 16 } 17 for (Integer count : distances.values()) { 18 result += count * (count - 1); //只有大于两条的才能有值.count个节点距离都相等,任选两条就可以与其它边一起构成会回形标。所以可以构成count * (count - 1)条 19 } 20 } 21 return result; 22 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!