LeetCode 356. Line Reflection

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值