Fork me on GitHub

Line Reflection

Description

Given n points on a 2D plane, find if there is such a line parallel to y-axis that reflect the given points.

Example 1:

1
2
Input: [[1,1],[-1,1]]
Output: true

Example 2:

1
2
Input: [[1,1],[-1,-1]]
Output: false

Solution

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
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points) {
if (points.size() == 0) return true;

unordered_map<int, set<int>> mapping;
for (auto& point : points) mapping[point.second].insert(point.first);

auto iter = mapping.begin();
auto left = iter->second.begin();
auto right = iter->second.rbegin();
int target = *left + *right;

while(iter != mapping.end()) {
auto& lis = iter->second;
left = lis.begin();
right = lis.rbegin();
while (left != lis.end() && right != lis.rend() && *left <= *right) {
if (*left + *right != target) return false;
++left; ++right;
}
++iter;
}
return true;
}
};