【Leetcode】447. Number of Boomerangs

来源:互联网 发布:套接字编程 编辑:程序博客网 时间:2024/05/01 23:20

思路:

(1)对每个点,用一个Map存储到它的距离相等的点的个数(距离到点数的映射)。

(2)对每个点,遍历其他点,更新到该点距离相等的点的个数。

(3)遍历Map,若到某点距离相等的点的个数count不小于2,则总数result加上count * (count - 1)。

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<Integer, Integer>();            for (int j = 0; j < points.length; j++) {                if (j == i)                    continue;                int distance = getDistance(points[i], points[j]);                if (map.containsKey(distance))                    map.put(distance, map.get(distance) + 1);                else                    map.put(distance, 1);            }            Set set = map.keySet();            Iterator<Integer> it = set.iterator();            while (it.hasNext()) {                int count = map.get(it.next());                if (count >= 2)                    result += count * (count - 1);            }        }        return result;    }    public int getDistance(int[] point1, int[] point2) {        return (point1[0]-point2[0]) * (point1[0]-point2[0]) + (point1[1]-point2[1]) * (point1[1]-point2[1]);    }}

Runtime:327ms

1 0
原创粉丝点击