Number of Boomerangs

来源:互联网 发布:广东省网络医院待遇 编辑:程序博客网 时间:2024/06/05 12:00

https://leetcode.com/problems/number-of-boomerangs/#/description

题目思想:
题目输入n个平面的点,要我们输出有多少个“boomerang”。一个boomerang是指平面上的一组点(i, j, k),i到j的距离等于i到k的距离,且j,k是有顺序的,即(i, j, k)和(i, k, j)不是同一个。
枚举每一个点到其它点的距离,然后用map保存。map的key值保存两点间的距离,map的value值则保存与该点的距离为key值的点有多少个。最后遍历map,用排列组合算出有多少个组合,并用sum存储并返回。

public class Solution {    public int numberOfBoomerangs(int[][] points) {        int sum = 0;        for(int i = 0; i < points.length; i++) {            Map<Double, Integer> map = new HashMap<Double, Integer>();            for(int j = 0; j < points.length; j++) {                double distance = Math.pow(points[i][0] - points[j][0], 2)                        + Math.pow(points[i][1] - points[j][1], 2);                if(map.containsKey(distance)) {                    map.put(distance, map.get(distance)+1);                }else {                    map.put(distance, 1);                }            }            for(Double d : map.keySet()) {                int n = map.get(d);                sum += n*(n-1);            }        }        return sum;    }}