-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number of Boomerangs
75 lines (67 loc) · 2.17 KB
/
Number of Boomerangs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
LeetCode 447:
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]]
Solution:
Language: C++
Tag: hashmap
*/
class Solution {
public:
int numberOfBoomerangs(vector<pair<int, int>>& points) {
/*
// 1. brute force -- O(n^3) time + O(1) space -- Time Limit Exceed
int res = 0;
for (int i = 0; i < points.size(); ++i) {
for (int j = 0; j < points.size(); ++j) {
if (i == j) {
continue;
}
int dist1 = dist(points[i], points[j]);
for (int k = 0; k < points.size(); ++k) {
if (k == i || k == j) {
continue;
}
if (dist1 == dist(points[i], points[k])) {
++res;
}
}
}
}
return res;
*/
// 2. hash -- O(n^2) time + O(n) space
int res = 0;
unordered_map<int, int> hash;
for (int i = 0; i < points.size(); ++i) {
hash.clear();
for (int j = 0; j < points.size(); ++j) {
if (i == j) {
continue;
}
int dist1 = dist(points[i], points[j]);
if (hash.find(dist1) == hash.end()) {
hash[dist1] = 1;
} else {
++hash[dist1];
}
}
for (pair<int, int> item : hash) {
res += (item.second) * (item.second - 1);
}
}
return res;
}
int dist(pair<int, int> &A, pair<int, int> &B) {
int x = A.first - B.first;
int y = A.second - B.second;
return ((x * x) + (y * y));
}
};