391-完美的矩形

Description:

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)).


这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述


问题描述:

给定N个矩形,判断它们是否正好(注意是正好,存在相交的多于区域也不行)形成一个矩形区域
每一个矩形由左下角和右上角的点的坐标进行表示,例如一个单位正方形表示为[1, 1, 2, 2](左下角的点的坐标为(1, 1), 右上角的点的坐标为(2, 2))


问题分析:

N个矩形正好构成一个矩形区域需要满足2个条件

  1. 所有小矩形的面积加起来等于大矩形的面积(显而易见)

  2. 四个顶点唯一,其他的点成对出现

我们只需要检查是否满足这两个性质就可以了


解法:

class Solution {
    public boolean isRectangleCover(int[][] rectangles) {
        //(x1, y1)为左下角顶点,(x2, y2)为右上角顶点
        int x1 = Integer.MAX_VALUE, y1 = Integer.MAX_VALUE, x2 = Integer.MIN_VALUE, y2 = Integer.MIN_VALUE;
        //sum为所有的矩形的面积之和
        int sum = 0;
        //保存见过的点
        Set<String> set = new HashSet();

        for(int[] rec : rectangles){
            x1 = Math.min(x1, rec[0]);
            y1 = Math.min(y1, rec[1]);
            x2 = Math.max(x2, rec[2]);
            y2 = Math.max(y2, rec[3]);

            sum += (rec[2] - rec[0]) * (rec[3] - rec[1]);

            String s1 = rec[0] + "" + rec[1];
            String s2 = rec[0] + "" + rec[3];
            String s3 = rec[2] + "" + rec[3];
            String s4 = rec[2] + "" + rec[1];
            //若见过该点,则一定不是顶点,删除
            if(!set.add(s1))    set.remove(s1);
            if(!set.add(s2))    set.remove(s2);
            if(!set.add(s3))    set.remove(s3);
            if(!set.add(s4))    set.remove(s4);
        }
        //判断顶点是否只有一个并且set中是否只有4个顶点(因为其他点为2个,都被删除了)
        if(!set.contains(x1 + "" + y1) || !set.contains(x1 + "" + y2) || !set.contains(x2 + "" + y2) || !set.contains(x2 + "" + y1) || !(set.size() == 4))  return false;
        //判断所有矩形面积之和是否等于矩形区域的面积
        return sum == (x2 - x1) * (y2- y1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值