public class Solution { /// <summary> /// 计算两个点的距离 /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <returns></returns> private double getDistance(int x1, int y1, int x2, int y2) { var dis = (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1); return dis; } /// <summary> /// 计算n的阶乘 /// </summary> /// <param name="n"></param> /// <returns></returns> private int SetpNum(int n) { int sum = 1; while (n != 1) { sum *= n; n = n - 1; } return sum; } public int NumberOfBoomerangs(int[,] points) { var pointcount = points.GetLength(0);//点个数 var dim = points.GetLength(1);//每组个点的坐标维数 List<KeyValuePair<int, int>> list = new List<KeyValuePair<int, int>>(); for (int i = 0; i < pointcount; i++) { var point = new KeyValuePair<int, int>(points[i, 0], points[i, 1]); list.Add(point); } //var dic = new Dictionary<KeyValuePair<int, int>, Dictionary<double, List<KeyValuePair<int, int>>>>(); var dic = new Dictionary<KeyValuePair<int, int>, Dictionary<double, int>>(); for (int i = 0; i < list.Count; i++) { for (int j = i; j < list.Count; j++) { if (i != j) { var curentPoint = list[i];//主点 var otherPoint = list[j];//从点 var dis = getDistance(list[i].Key, list[i].Value, list[j].Key, list[j].Value);//dis值是同一个 #region 主点处理 if (!dic.ContainsKey(curentPoint)) { //dic.Add(curentPoint, new Dictionary<double, List<KeyValuePair<int, int>>>()); //dic[curentPoint].Add(dis, new List<KeyValuePair<int, int>>()); //dic[curentPoint][dis].Add(list[j]); dic.Add(curentPoint, new Dictionary<double, int>()); dic[curentPoint].Add(dis, 1); } else { if (!dic[curentPoint].ContainsKey(dis)) { //dic[curentPoint].Add(dis, new List<KeyValuePair<int, int>>()); //dic[curentPoint][dis].Add(list[j]); dic[curentPoint].Add(dis, 1); } else { //dic[curentPoint][dis].Add(list[j]); dic[curentPoint][dis]++; } } #endregion 主点处理 #region 从点处理 if (!dic.ContainsKey(otherPoint)) { //dic.Add(otherPoint, new Dictionary<double, List<KeyValuePair<int, int>>>()); //dic[otherPoint].Add(dis, new List<KeyValuePair<int, int>>()); //dic[otherPoint][dis].Add(list[i]); dic.Add(otherPoint, new Dictionary<double, int>()); dic[otherPoint].Add(dis, 1); } else { if (!dic[otherPoint].ContainsKey(dis)) { //dic[otherPoint].Add(dis, new List<KeyValuePair<int, int>>()); //dic[otherPoint][dis].Add(list[i]); dic[otherPoint].Add(dis, 1); } else { //dic[otherPoint][dis].Add(list[i]); dic[otherPoint][dis]++; } } #endregion 从点处理 } } } var sum = 0; foreach (var d in dic) { foreach (var d2 in d.Value) { if (d2.Value > 1) { var ct = d2.Value; //计算从Count中任取2个的排列数即A(count)(2) sum += ct * (ct - 1); } } } return sum; } }
https://leetcode.com/problems/number-of-boomerangs/#/description