leetcode:356. 直线对称

题目解析

题目描述

在一个二维平面空间中,给你 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;
    }
};

类似题目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值