447. Number of Boomerangs

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.

Rust Solution

struct Solution;

use std::collections::HashMap;

impl Solution {
    fn distance_square(a: &[i32], b: &[i32]) -> i32 {
        (a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1])
    }
    fn number_of_boomerangs(points: Vec<Vec<i32>>) -> i32 {
        let n = points.len();
        let mut hm: HashMap<i32, i32> = HashMap::new();
        let mut sum = 0;
        for i in 0..n {
            for j in 0..n {
                if i == j {
                    continue;
                }
                let a = &points[i];
                let b = &points[j];
                let distance_square = Self::distance_square(a, b);
                let ea = hm.entry(distance_square).or_default();
                *ea += 1;
            }
            for &value in hm.values() {
                if value > 1 {
                    sum += value * (value - 1);
                }
            }
            hm.clear();
        }
        sum
    }
}

#[test]
fn test() {
    let points: Vec<Vec<i32>> = vec_vec_i32![[0, 0], [1, 0], [2, 0]];
    assert_eq!(Solution::number_of_boomerangs(points), 2);
}

Having problems with this solution? Click here to submit an issue on github.