-
Notifications
You must be signed in to change notification settings - Fork 10
/
line-reflection.cpp
59 lines (56 loc) · 1.79 KB
/
line-reflection.cpp
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
// Time: O(n)
// Space: O(n)
// Hash solution.
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points) {
if (points.empty()) {
return true;
}
unordered_map<int, unordered_set<int>> groups_by_y;
int left = numeric_limits<int>::max();
int right = numeric_limits<int>::min();
for (const auto& p : points) {
groups_by_y[p.second].emplace(p.first);
left = min(left, p.first);
right = max(right, p.first);
}
const auto mid = left + right;
for (const auto& kvp : groups_by_y) {
for (const auto& x : kvp.second) {
if (kvp.second.count(mid - x) == 0) {
return false;
}
}
}
return true;
}
};
// Time: O(nlogn)
// Space: O(1)
// Two pointers solution.
class Solution2 {
public:
bool isReflected(vector<pair<int, int>>& points) {
if (points.empty()) {
return true;
}
sort(points.begin(), points.end());
sort(points.begin(), points.begin() + distance(points.begin(), points.end()) / 2,
[](const pair<int, int>& a, const pair<int, int>& b) {
if (a.first == b.first) {
return a.second > b.second;
}
return a.first < b.first;
});
const auto mid = points.front().first + points.back().first;
for (int left = 0, right = points.size() - 1; left <= right; ++left, --right) {
if ((mid != points[left].first + points[right].first) ||
(points[left].first != points[right].first &&
points[left].second != points[right].second)) {
return false;
}
}
return true;
}
};