[Leetcode] 391. Perfect Rectangle 解题报告

来源:互联网 发布:华师网络教育平台 编辑:程序博客网 时间:2024/06/05 21:05

题目

Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.

Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).

Example 1:

rectangles = [  [1,1,3,3],  [3,1,4,2],  [3,2,4,4],  [1,3,2,4],  [2,3,3,4]]Return true. All 5 rectangles together form an exact cover of a rectangular region.

Example 2:

rectangles = [  [1,1,2,3],  [1,3,2,4],  [3,1,4,2],  [3,2,4,4]]Return false. Because there is a gap between the two rectangular regions.

Example 3:

rectangles = [  [1,1,3,3],  [3,1,4,2],  [1,3,2,4],  [3,2,4,4]]Return false. Because there is a gap in the top center.

Example 4:

rectangles = [  [1,1,3,3],  [3,1,4,2],  [1,3,2,4],  [2,2,4,4]]Return false. Because two of the rectangles overlap with each other.

思路

自己的笨办法就是先计算所有小矩阵的面积和,以及四个边界构成的面积,如果不相等就直接返回false。接下来就需要判断是否有重合:如果要求空间复杂度是O(1),就可以两两检查矩形,这样时间复杂度是O(n^2);如果允许空间复杂度是O(n^2),那么可以初始化四个边界构成的矩阵,然后把每个矩阵“往上贴”,贴的过程中如果发现某个位置已经被其他矩阵覆盖,则返回false。当然这种算法不能通过大数据测试,我们需要更聪明的方法。

小榕流光的这篇帖子http://blog.csdn.net/qq508618087/article/details/52483625图文并茂,解释的很详细,为了不构成侵权,请参考我给出的网址^_^。这种算法的时间复杂度是O(n)。

代码

class Solution {public:    bool isRectangleCover(vector<vector<int>>& rectangles) {        unordered_map<string, int> hash;          for(auto val: rectangles) {              for(int i = 0; i < 4; i++) {                  string tem = to_string(val[i / 2 * 2]) + ','+to_string(val[i % 2 * 2 + 1]);                  if(hash[tem] & (1 << i)) {            // already another corner with the same index                    return false;                  }                hash[tem] |= (1 << i);              }          }          int cntCorner = 0;          for(auto& val: hash) {              int sec = val.second;              if(!(sec & (sec - 1)) && cntCorner++ > 4)  {                        // When the point is the corner                return false;            }            if((sec&(sec-1)) && !(sec==3||sec==12||sec==5||sec==10||sec==15)) { // when the point is not the corner                return false;             }        }          return true;      }};

原创粉丝点击