首页 > 代码库 > 447. 求回旋镖坐标的数量 NumberOfBoomerangs
447. 求回旋镖坐标的数量 NumberOfBoomerangs
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]]
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/67102/c-hashtable-solution-o-n-2-time-o-n-space-with-explaination/2
https://discuss.leetcode.com/topic/68139/simple-java-solution-using-hashmap-beats-90/3
447. 求回旋镖坐标的数量 NumberOfBoomerangs