447. Number of Boomerangs

来源:互联网 发布:java ssh2 编辑:程序博客网 时间:2024/06/13 02:37

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:2Explanation:The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]

遍历每个point,然后找和它等距离的其他point,按距离来保存,比如有一个点a,和它距离都是1的点有b,c,d,那么一共的组合就有6种,包括:[a, b, c], [a, c, b], [a, b, d], [a, d, b], [a, c, d], [a, d, c]。这么算是不考重复的情况下。还有可能b, c坐标完全相同,那么b和c会被当成两个点算两次。

public class Solution {    public int numberOfBoomerangs(int[][] points) {               int result = 0;        for(int i = 0; i < points.length; i++) {            Map<Integer, Integer> map = new HashMap();            for(int j = 0; j < points.length; j++) {                if(i == j) continue;                int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];                int distance = dx * dx + dy * dy;                map.put(distance, map.getOrDefault(distance, 0) + 1);            }            for(int k : map.keySet()) {                int n = map.get(k);                result += n * (n - 1);            }        }                return result;    }}
原创粉丝点击