447. Number of Boomerangs
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了447. Number of Boomerangs相关的知识,希望对你有一定的参考价值。
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 i
and 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]]
Approach #1: C++. Using triple cycle .[Time Limit Exceeded]
class Solution { public: int numberOfBoomerangs(vector<pair<int, int>>& points) { int size = points.size(); int counter = 0; for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { if (i == j) continue; for (int k = 0; k < size; ++k) { if (i == k || j == k) continue; int x1 = abs(points[i].first - points[j].first); int x2 = abs(points[i].first - points[k].first); int y1 = abs(points[i].second - points[j].second); int y2 = abs(points[i].second - points[k].second); double fs = sqrt(pow(x1, 2) + pow(y1, 2)); double ft = sqrt(pow(x2, 2) + pow(y2, 2)); if (fs == ft) counter++; } } } return counter; } };
Approach #2: C++.
class Solution { public: int numberOfBoomerangs(vector<pair<int, int>>& points) { int size = points.size(); int counter = 0; for (int i = 0; i < size; ++i) { unordered_map<int, int> distances; for (int j = 0; j < size; ++j) { if (i == j) continue; int distance = (points[i].first - points[j].first) * (points[i].first - points[j].first) + (points[i].second - points[j].second) * (points[i].second - points[j].second); distances[distance]++; } for (auto& p : distances) { if (p.second > 1) counter += p.second * (p.second - 1); } } return counter; } };
Approach #2: Java.
class Solution { public int numberOfBoomerangs(int[][] points) { int res = 0; for (int i = 0; i < points.length; ++i) { HashMap<Integer, Integer> map = new HashMap<>(); for (int j = 0; j < points.length; ++j) { if (points[i] == points[j]) continue; int dx = points[i][0] - points[j][0]; int dy = points[i][1] - points[j][1]; int d = dx * dx + dy * dy; map.put(d, map.getOrDefault(d, 0) + 1); } for (int val : map.values()) { res += val * (val - 1); } } return res; } }
Approach #3: Python.
class Solution(object): def numberOfBoomerangs(self, points): """ :type points: List[List[int]] :rtype: int """ res = 0 for p in points: cmap = {} for q in points: f = p[0] - q[0] s = p[1] - q[1] cmap[f*f + s*s] = 1 + cmap.get(f*f + s*s, 0) for k in cmap: res += cmap[k] * (cmap[k] - 1) return res
Time Submitted | Status | Runtime | Language |
---|---|---|---|
a few seconds ago | Accepted | 241 ms | java |
5 minutes ago | Accepted | 1436 ms | python |
8 minutes ago | Accepted | 196 ms | cpp |
以上是关于447. Number of Boomerangs的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 447 Number of Boomerangs