[LeetCode]391. Perfect Rectangle

https://leetcode.com/problems/perfect-rectangle/#/description

给一组矩形,矩形由右下和左上两个点确定唯一,判断这些矩形组合而成是否还是矩形





true的条件有两个:1、每个矩形的size和为大矩形四个点计算的和;2、set中只有四个点,而且这四个点是x1/x2/y1/y2所确定的点

每个矩形四个点加到set中,遇到重复就移除。

public class Solution {
    public boolean isRectangleCover(int[][] rectangles) {
        HashSet<String> set = new HashSet();
        int x1 = Integer.MAX_VALUE;
        int y1 = Integer.MAX_VALUE;
        int x2 = Integer.MIN_VALUE;
        int y2 = Integer.MIN_VALUE;
        int area = 0;
        for (int[] rec : rectangles) {
            x1 = Math.min(rec[0], x1);
            y1 = Math.min(rec[1], y1);
            x2 = Math.max(rec[2], x2);
            y2 = Math.max(rec[3], y2);
            area += (rec[2] - rec[0]) * (rec[3] - rec[1]);
            String s1 = rec[0] + " " + rec[3];
            String s2 = rec[0] + " " + rec[1];
            String s3 = rec[2] + " " + rec[1];
            String s4 = rec[2] + " " + rec[3];
            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);
            }
        }
        if (!set.contains(x1 + " " + y1) || !set.contains(x2 + " " + y1) || !set.contains(x1 + " " + y2) || !set.contains(x2 + " " + y2) || set.size() != 4) {
            return false;
        }
        return area == (x2 - x1) * (y2 - y1);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值