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 iand 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: 2 Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]]
题意:定义一种类似“回形标”的三元组结构,即在三元组(i, j, k)中i和j之间的距离与i和k之间的距离相等。找到一组坐标数据中,可构成几组这样的“回形标”结构。
思路:遍历每一个点,用字典存储距离相同的点的数量
根据数量,运用排列组合公式N*(N-1) ,计算回旋镖的可组成数量
For those that don't understand how groupCount * (groupCount + 1) became N * (N - 1):
algorithm actually sets groupCount to zero for the first point, 1 for the second point, etc. So, if N == groupCount + 1
N * (N - 1)
== (groupCount + 1) * ((groupCount + 1) - 1)
== (groupCount + 1) * (groupCount)
== groupCount * (groupCount + 1)
static public int NumberOfBoomerangs(int[,] points) {
int number = 0;
int disSqrt = 0;
int count = points.GetLength(0);
for (int i = 0; i < count; i++) {
Dictionary<int, int> dic = new Dictionary<int, int>();
for (int j = 0; j < count; j++) {
if (i == j) {
continue;
}
disSqrt = (points[i, 0] - points[j, 0]) * (points[i, 0] - points[j, 0]) -
(points[i, 1] - points[j, 1]) * (points[i, 1] - points[j, 1]);
if (dic.ContainsKey(disSqrt)) {
dic[disSqrt]++;
} else {
dic[disSqrt] = 0;
}
}
foreach (int value in dic.Values) {
number += value * (value + 1);
}
}
return number;
}
https://discuss.leetcode.com/topic/68139/simple-java-solution-using-hashmap-beats-90/3