Skip to content

Latest commit

 

History

History
108 lines (85 loc) · 3.05 KB

File metadata and controls

108 lines (85 loc) · 3.05 KB

中文文档

Description

You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. 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).

Return the number of boomerangs.

 

Example 1:

Input: points = [[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]].

Example 2:

Input: points = [[1,1],[2,2],[3,3]]
Output: 2

Example 3:

Input: points = [[1,1]]
Output: 0

 

Constraints:

  • n == points.length
  • 1 <= n <= 500
  • points[i].length == 2
  • -104 <= xi, yi <= 104
  • All the points are unique.

Solutions

Python3

class Solution:
    def numberOfBoomerangs(self, points: List[List[int]]) -> int:
        n = len(points)
        if n < 3:
            return 0
        number = 0
        for i in range(n):
            distance_counter = collections.Counter()
            for j in range(n):
                if i == j:
                    continue
                x1, y1 = points[i][0], points[i][1]
                x2, y2 = points[j][0], points[j][1]
                distance = (x1 - x2) ** 2 + (y1 - y2) ** 2
                distance_counter[distance] += 1
            number += sum([val * (val - 1) for val in distance_counter.values()])
        return number

Java

class Solution {
    public int numberOfBoomerangs(int[][] points) {
        int n = points.length;
        if (n < 3) {
            return 0;
        }
        int number = 0;
        for (int i = 0; i < n; ++i) {
            Map<Integer, Integer> distanceCounter = new HashMap<>();
            for (int j = 0; j < n; ++j) {
                if (i == j) {
                    continue;
                }
                int x1 = points[i][0], y1 = points[i][1];
                int x2 = points[j][0], y2 = points[j][1];
                int distance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
                distanceCounter.put(distance, distanceCounter.getOrDefault(distance, 0) + 1);
            }
            for (int val : distanceCounter.values()) {
                number += val * (val - 1);
            }
        }
        return number;
    }
}

...