算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 回旋镖的数量,我们先来看题面:
https://leetcode-cn.com/problems/number-of-boomerangs/
You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. 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).
Return the number of boomerangs.
给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。
返回平面上所有回旋镖的数量。
示例
示例 1:
输入:points = [[0,0],[1,0],[2,0]]
输出:2
解释:两个回旋镖为 [[1,0],[0,0],[2,0]] 和 [[1,0],[2,0],[0,0]]
示例 2:
输入:points = [[1,1],[2,2],[3,3]]
输出:2
示例 3:
输入:points = [[1,1]]
输出:0
解题
将每个点作为第一个点进行遍历,并统计相同距离的点个数;
每个距离作为键,点个数作为值,故而采用哈希表的方式进行存储;
如果存在n个点与某一点的距离相等,则由排列组合可得n*(n-1)种排列方式,即存在n*(n-1)种回旋镖
class Solution {
public static int numberOfBoomerangs(int[][] points) {
int len=points.length;
int res=0;
HashMap<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
for(int i=0;i<len;i++){
for(int j=0;j<len;j++){
if(i!=j){
int x=points[i][0]-points[j][0];
int y=points[i][1]-points[j][1];
int dist=x*x+y*y;
if(hashMap.containsKey(dist)){
hashMap.put(dist,hashMap.get(dist)+1);
}else{
hashMap.put(dist,1);
}
}
}
for(Integer count:hashMap.values()){
res+=count*(count-1);
}
hashMap.clear();
}
return res;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: