LeetCode "Line Reflection"

First you find the Y, and then do a pairing game - hashtable is good.

class Solution {
public:
    bool isReflected(vector<pair<int, int>>& points)
    {
        int n = points.size();
        if (n < 2) return true;

        unordered_map<int, unordered_map<int, int>> hm; // y - [x, cnt]
        int minx = INT_MAX, maxx = INT_MIN;
        for (auto &pr : points)
        {
            minx = min(minx, pr.first);
            maxx = max(maxx, pr.first);

            hm[pr.second][pr.first] ++;
        }
        if (minx == maxx) return true;

        int midx2 = (minx + maxx);
        for (auto &pr : points)
        {
            int x = pr.first;
            int y = pr.second;

            // paired already?
            if (hm.find(y) == hm.end() || hm[y].find(x) == hm[y].end()) 
                continue;
            
            if (x * 2 == midx2)
            {
                hm[y].erase(x);
            }
            else
            {
                int x2 = midx2 - x;
                if (hm[y].find(x2) != hm[y].end())
                {
                    hm[y][x] --;
                    if (!hm[y][x])    hm[y].erase(x);
                    
                    hm[y][x2] --;
                    if (!hm[y][x2])    hm[y].erase(x2);
                }
            }

            if (!hm[y].size())    hm.erase(y);
        }

        return hm.empty();
    }
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/5586102.html