very straight forward.
#include <vector>
#include <iostream>
using namespace std;
/*
Given n points on a 2D plane and find if there is such a line parallel to y-axis that reflect the given set of points.
Example:
Given points = [[1, 1], [-1, 1]] return true;
Given points = [[1, 1], [-1, -1]] return false;
*/
/*
Think that, if all points are reflect each other. We need to first find the line. The line should be in the middle of (min, max).
For other points, if two point reflect, the y-ith should be same, (min, max) / 2 - x1 = (min, max) / 2 - x2.
*/
bool isReflected(vector< pair<int, int> >& points) {
unordered_map< int, set<int> > m;
int minX = INT_MAX, maxX = INT_MIN;
for(int i = 0; i < points.size(); ++i) {
minX = min(points[i].first, minX);
maxX = max(points[i].first, maxX);
m[points[i].first].insert(points[i].second);
}
double y = double(maxX + minX) / 2;
for(int i = 0; i < points.size(); ++i) {
int t = 2*y - points[i].first;
if(!m.count(t) || !m[t].count(points[i].second)) return false;
}
return true;
}
// second method
bool isReflectedII(vector<pair<int, int> >& points) {
if(point.size() == 0) return true;
set< pair<int, int> > res;
double y = 0;
for(auto a : points) {
res.insert(a);
y += a.first;
}
y = y / points.size();
for(auto a : res) {
if(!res.count((2 * y - a.first), a.second)) return false;
}
return true;
}
本文介绍了一种算法,用于判断一组二维平面上的点是否关于一条平行于y轴的直线呈镜面对称分布。通过寻找中间直线并验证每一点与其镜像点是否存在来实现。
305

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



