题目:
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]]分析:
class Solution {
public int numberOfBoomerangs(int[][] points) {
//给定坐标数组,找出i到j的距离等i到k的距离,满足这样的三个坐标点共有多少对(返回的结果都是偶数对,BAC和BCA是属于一对)
//思路:使用HashMap存储<它到其他点的距离,次数>,BAC,ACB is a pairs of arrays
//注意:暴力解法肯定TLM,必须使用距离相同作为其叠加的一句
if(points.length==0||points==null)return 0;
int count=0;
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
for(int i=0;i<points.length;i++){
for(int j=0;j<points.length;j++){
if(i==j)continue;
int d=distance(points[i],points[j]);
hm.put(d,hm.getOrDefault(d,0)+1);
}
for(int val:hm.values()){
//图论的计算规则,相同的路径,不同的组合为val*(val-1)
count+=val*(val-1);
}
hm.clear();
}
return count;
}
public int distance(int[] x,int [] y){
return (x[0]-y[0])*(x[0]-y[0])+(x[1]-y[1])*(x[1]-y[1]);
}
}
本文介绍了一种高效算法,用于解决给定平面上n个互不相同的点中找到所有回旋镖问题。通过利用哈希映射来记录每个点与其他点之间的距离出现的频次,进而快速计算出所有满足条件的回旋镖数量。

254

被折叠的 条评论
为什么被折叠?



