leetcode 447. Number of Boomerangs---java

题目:

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和i,k中均含有i这一公共元素,因此,我们以此为出发点。依次遍历每一组数据,并计算其余元素距该点的距离值(为避免开根号后的小数误差,这里只计算平方和即可),并通过HashMap记录距离,其中key为距离,value为距离出现的次数;每遍历一组数据,记录一次,并计算此时符合题意得次数(由于是有序的,因此次数=value*(value-1)+之前次数),注意计算次数后需要清空HashMap中数据。

程序:

class Solution {
    public int numberOfBoomerangs(int[][] points) {
        
        int result = 0;
        HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();
        
        for(int i = 0; i < points.length; i++){  //遍历第i组数据
            for(int j = 0; j < points.length; j++){  //遍历其余数据
                if(i != j ){
                    int distance = dis(points[i],points[j]);  //调用方法计算距离
                    if(record.containsKey(distance))  //更改Map记录
                        record.put(distance,record.get(distance)+1);
                    else 
                        record.put(distance,1);
                }
            }
            
            for(int value: record.values()) //遍历Map,计算result
                result += value * (value-1);
            
            record.clear();  //清空Map
        }
        
        return result;
    }
    
    private int dis(int []point1 , int []point2){ //计算距离
        
        int distance = (point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]) * (point1[1] - point2[1]);
        
        return distance;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值