classSolution: defnumberOfBoomerangs(self, points: List[List[int]]) -> int: ans = 0 for p in points: cnt = defaultdict(int) for q in points: dis = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]) cnt[dis] += 1 for m in cnt.values(): ans += m * (m - 1) return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intnumberOfBoomerangs(vector<vector<int>> &points){ int ans = 0; for (auto &p : points) { unordered_map<int, int> cnt; for (auto &q : points) { int dis = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]); ++cnt[dis]; } for (auto &[_, m] : cnt) { ans += m * (m - 1); } } return ans; } };
publicclassSolution { publicintNumberOfBoomerangs(int[][] points) { int ans = 0; foreach (int[] p in points) { Dictionary<int, int> cnt = new Dictionary<int, int>(); foreach (int[] q in points) { int dis = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]); if (!cnt.ContainsKey(dis)) { cnt.Add(dis, 1); } else { ++cnt[dis]; } } foreach (KeyValuePair<int, int> kv in cnt) { int m = kv.Value; ans += m * (m - 1); } } return ans; } }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcnumberOfBoomerangs(points [][]int) (ans int) { for _, p := range points { cnt := map[int]int{} for _, q := range points { dis := (p[0]-q[0])*(p[0]-q[0]) + (p[1]-q[1])*(p[1]-q[1]) cnt[dis]++ } for _, m := range cnt { ans += m * (m - 1) } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
var numberOfBoomerangs = function(points) { let ans = 0; for (const p of points) { const cnt = newMap(); for (const q of points) { const dis = (p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1]); cnt.set(dis, (cnt.get(dis) || 0) + 1); } for (const [_, m] of cnt.entries()) { ans += m * (m - 1); } } return ans; };