题目解析
题目描述
在一个二维平面空间中,给你 n 个点的坐标。
问,是否能找出一条平行于 y 轴的直线,让这些点关于这条直线成镜像排布?
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points){
}
};
题目解析
思路一(但是没有保证没有重复的点,如果出现重复的点没有关系,对应map的value只插一个)
思路
- 先找到所有点的横坐标的最大值和最小值,那么二者的均值就是中间直线的横坐标
- 然后遍历每个点,如果都能找到直线对称的另一个点,则返回true,否则返回false
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points){
std::unordered_map<int, std::set<int>> m;
int max = INT_MIN, min = INT_MAX;
for(auto a : points){
max = std::max(max, a.first);
min = std::min(min, a.first);
m[a.first].insert(a.second);
}
double y = (double)(max + min) / 2;
for(auto a : points){
int t = 2 * y - a.first; // 求出对称的那个点的x坐标
if(!m.count(t) || !m[t].count(a.second)){ // 如果对称的x坐标不存在 || 对称的x指标的y指标和当前坐标不相同
return false;
}
}
return true;
}
};
思路
- 下面这种解法没有求最大值和最小值,而是把所有的横坐标累加起来,然后求平均数,基本思路都相同
class Solution {
public:
bool isReflected(vector<pair<int, int>>& points){
if(points.empty()){
return true;
}
std::set<std::pair<int, int>> pts;
double y = 0;
for(auto a : points){
pts.insert(a);
y += a.first;
}
y /= points.size();
for(auto a : pts){
if (!pts.count({y * 2 - a.first, a.second})) {
return false;
}
}
return true;
}
};