concise C++ solution


  • 0
    N

    My solution is based on hxtang's counting-corner-method. For the details of this method, please refer to https://discuss.leetcode.com/topic/55923/o-n-solution-by-counting-corners-with-detailed-explaination

    I did some improvement to make the code more concise. The main idea is to use the area of rectangles to check if overlaps exist.

    class Solution {
    public:
        bool isRectangleCover(vector<vector<int>>& rectangles) {
            int x1 = INT_MAX, y1 = INT_MAX, x2 = INT_MIN, y2 = INT_MIN, area = 0;
            unordered_map<string, int> hash;
            for (auto& r : rectangles){
                x1 = min(x1, r[0]);
                y1 = min(y1, r[1]);
                x2 = max(x2, r[2]);
                y2 = max(y2, r[3]);
                area += (r[3] - r[1]) * (r[2] - r[0]);
                hash[to_string(r[0]) + "#" + to_string(r[1])] ++;
                hash[to_string(r[0]) + "#" + to_string(r[3])] ++;
                hash[to_string(r[2]) + "#" + to_string(r[1])] ++;
                hash[to_string(r[2]) + "#" + to_string(r[3])] ++;
            }
            if (area != (y2 - y1) * (x2 - x1)) return false;
            if (hash[to_string(x1) + "#" + to_string(y1)] ++ != 1) return false;
            if (hash[to_string(x1) + "#" + to_string(y2)] ++ != 1) return false;
            if (hash[to_string(x2) + "#" + to_string(y1)] ++ != 1) return false;
            if (hash[to_string(x2) + "#" + to_string(y2)] ++ != 1) return false;
            for (auto& p : hash)
                if (p.second != 2 && p.second != 4) return false;
            return true;
        }
    };
    

Log in to reply
 

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