Concise C++ solution using unordered_map


  • 0
    W
    class Solution {
    public:
        bool isReflected(vector<pair<int, int>>& points) {
            int minx=INT_MAX, maxx=INT_MIN;
            unordered_map<int,int> point_map;
            for(auto point:points){
                minx=min(minx,point.first);
                maxx=max(maxx,point.first);
                point_map[point.first]=point.second;
            }
            for(auto iter=point_map.begin();iter!=point_map.end();iter++){
                int to_find=minx+maxx-iter->first;
                if(point_map.find(to_find)==point_map.end() || point_map[to_find]!=iter->second){
                    return false;
                }
            }
            return true;
        }
    };
    

  • 1
    E

    what if some points have the same x value? You answer only keeps one point with a specific x value.


  • 0
    W

    I did some fix for your solution:

    class Solution {
    public:
        bool isReflected(vector<pair<int, int>>& points) {
            if (points.size() < 2) return true;
            int maxVal = std::numeric_limits<int>::min();
            int minVal = std::numeric_limits<int>::max();
            unordered_map<int, unordered_set<int>> index;
            for(const auto& p : points) {
                minVal = min(minVal, p.first);
                maxVal = max(maxVal, p.first);
                auto it = index.find(p.first);
                if (it == index.end()) {
                    index[p.first] = {p.second};
                } else {
                    it->second.insert(p.second);
                }
            }
            double midVal = static_cast<double>(minVal + maxVal) / 2;
            for (auto it = index.begin(); it != index.end(); ++it) {
                int coVal = 2 * midVal - it->first;
                auto coIt = index.find(coVal);
                if (coIt == index.end() || coIt->second != it->second ) {
                    return false;
                }
            }
            return true;
        }
    };
    

  • 0
    W

    @eeriee Yes, in this problem, the points having same coordinates can be treated as one same point, for example, (-1,3), (1,3), (1,3) are symmetrical of y=0.


  • 1
    W

    This code is not correct. Counter example

    [[1,1],[-1,-1],[-1,1]]

    This should return false


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.