LeetCode #356. Line Reflection

本文探讨了一个算法问题:如何判断二维平面上的点集是否可以通过一条平行于Y轴的直线进行反射对称。通过分析输入点集,算法能够确定是否存在这样一条线,使得所有点关于这条线对称。文章提供了具体的代码实现,并讨论了其时间复杂度。

题目描述:


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值