题目描述:
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:
Input: [[1,1],[-1,1]]
Output: true
Example 2:
Input: [[1,1],[-1,-1]]
Output: false
Follow up:
Could you do better than O(n^2) ?
class Solution {
public:
bool isReflected(vector<vector<int>>& points) {
if(points.size()==0) return true;
int max_x=INT_MIN, min_x=INT_MAX;
// {x:{y:count}}, 如果要考虑多个相同的点,时间复杂度O(n)
// {x:y}, 如果多个相同的点算作一个点,时间复杂度O(n)
unordered_map<int,unordered_set<int>> m;
for(auto point:points)
{
max_x=max(max_x,point[0]);
min_x=min(min_x,point[0]);
m[point[0]].insert(point[1]);
}
int mid_x=max_x+min_x;
for(auto p:m)
{
int x1=p.first;
if(x1*2==mid_x) continue;
int x2=mid_x-x1;
if(m.count(x2)==0) return false;
for(int y:p.second)
{
if(m[x2].count(y)==0)
return false;
}
}
return true;
}
};
本文探讨了一个算法问题:如何判断二维平面上的点集是否可以通过一条平行于Y轴的直线进行反射对称。通过分析输入点集,算法能够确定是否存在这样一条线,使得所有点关于这条线对称。文章提供了具体的代码实现,并讨论了其时间复杂度。
4106

被折叠的 条评论
为什么被折叠?



