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]]
Analyse:
1. 首先想找两个点所连直线的垂直平分线,再判断其他的点是否在该垂直平分线上。O(n^3), 超时。
1 class Solution { 2 public: 3 int numberOfBoomerangs(vector<pair<int, int>>& points) { 4 // check all pairs accordingly 5 int count = 0; 6 for (int i = 0; i < points.size(); i++) { 7 for (int j = i + 1; j < points.size(); j++) { 8 for (int k = 0; k < points.size(); k++) { 9 if (k != i && k != j) { 10 if (isBoomerang(points[i], points[j], points[k])) 11 count++; 12 } 13 } 14 } 15 } 16 return count * 2; 17 } 18 19 bool isBoomerang(pair<int, int> point1, pair<int, int> point2, pair<int, int> checkMe) { 20 int x1 = point1.first, y1 = point1.second, x2 = point2.first, y2 = point2.second, x = checkMe.first, y = checkMe.second; 21 22 if (y1 == y2) { 23 return x * 2 == x1 + x2; 24 } else 25 return (x1 - x2) * 1.0 / (y2 - y1) * (2 * x - x1 - x2) + y1 + y2 == 2 * y; 26 } 27 };
2. 用hash table maintain point i到point j的距离,map该距离到count,for all i,j。对于每个i,如果该hash table的value >= 2,则取改value的全排列并更新result。O(n^2)
1 class Solution { 2 public: 3 int numberOfBoomerangs(vector<pair<int, int>>& points) { 4 int result = 0; 5 for (int i = 0; i < points.size(); i++) { 6 unordered_map<int, int> um; 7 for (int j = 0; j < points.size(); j++) { 8 if (i != j) { 9 int x = points[i].first - points[j].first; 10 int y = points[i].second - points[j].second; 11 um[x * x + y * y]++; 12 } 13 } 14 for (auto count : um) { 15 int n = count.second; 16 if (n >= 2) 17 result += n * (n - 1); // permutation 18 } 19 } 20 return result; 21 } 22 };