447. 回旋镖的数量

给定平面上 n 对 互不相同 的点 points ,其中 points[i] = [xi, yi] 。回旋镖 是由点 (i, j, k) 表示的元组 ,其中 i 和 j 之间的距离和 i 和 k 之间的欧式距离相等(需要考虑元组的顺序)。

返回平面上所有回旋镖的数量。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-boomerangs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.HashMap;
import java.util.Map;

class Solution {

    private int distance(int x1, int y1, int x2, int y2) {
        return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
    }

    public int numberOfBoomerangs(int[][] points) {
        if (points == null || points.length < 3) {
            return 0;
        }
        int ans = 0;
        for (int i = 0; i < points.length; ++i) {
            Map<Integer, Integer> cntMap = new HashMap<>();
            for (int j = 0; j < points.length; ++j) {
                if (i == j) {
                    continue;
                }
                int d = distance(points[i][0], points[i][1], points[j][0], points[j][1]);
                cntMap.put(d, cntMap.getOrDefault(d, 0) + 1);
            }
            for (Map.Entry<Integer, Integer> entry : cntMap.entrySet()) {
                ans += entry.getValue() * (entry.getValue() - 1);
            }
        }
        return ans;
    }
}
posted @ 2022-02-18 11:02  Tianyiya  阅读(48)  评论(0)    收藏  举报