• 391. Perfect Rectangle


    最后更新

    一刷
    16-Jan-2017

    这个题我甚至不知道该怎么总结。

    难就难在从这个题抽象出一种解法,看了别人的答案和思路= =然而没有归类总结到某种类型,这题相当于背了个题。。。

    简单的说,除了最外面的4个点,所有的点都会2次2次的出现,如果有覆盖,覆盖进去的点就不是成对出现了。

    最外面4个点围的面积等于所有小矩形面积的和。

    就用这2个判断就行了。

    判断成对的点用的SET,单次出现添加,第二次出现删除。。这样最后应该都删掉,SET里只剩下4个最外面的点。

    剩下的就是判断最外点,不停地更新。。

    public class Solution {
        public boolean isRectangleCover(int[][] rectangles) {
            if (rectangles.length == 0) return true;
            
            int left = Integer.MAX_VALUE;
            int bot = Integer.MAX_VALUE;
            int right = Integer.MIN_VALUE;
            int top = Integer.MIN_VALUE;
            Set<Integer> set = new HashSet<>();
            int tempArea = 0;
            
            for (int[] nums : rectangles) {
                // bot left top right
                bot = Math.min(bot, nums[0]);
                left = Math.min(left, nums[1]);
                top = Math.max(top, nums[2]);
                right = Math.max(right, nums[3]);
                
                tempArea += (nums[2] - nums[0]) * (nums[3] - nums[1]);
                int bottomLeft = 10 * nums[0] + nums[1];
                int topRight = 10 * nums[2] + nums[3];
                int bottomRight = 10 * nums[0] + nums[3];
                int topLeft = 10 * nums[2] + nums[1];
                
                if (set.contains(bottomLeft)) set.remove(bottomLeft);
                else set.add(bottomLeft);
                
                if (set.contains(topRight)) set.remove(topRight);
                else set.add(topRight);
                
                if (set.contains(bottomRight)) set.remove(bottomRight);
                else set.add(bottomRight);
                
                if (set.contains(topLeft)) set.remove(topLeft);
                else set.add(topLeft);
            }
            int bottomLeft = 10 * bot + left;
            int topRight = 10 * top + right;
            int bottomRight = 10 * bot + right;
            int topLeft = 10 * top + left;
            int maxArea = (right - left) * (top - bot);
            
            if(set.size() == 4 && set.contains(bottomLeft) && set.contains(topRight) 
                               && set.contains(bottomRight) && set.contains(topLeft)) {
                return maxArea == tempArea;                           
            } else {
                return false;
            }
        }
    }
    
  • 相关阅读:
    《第一行代码》学习笔记18-广播接收器Broadcast_Receiver(1)
    《第一行代码》学习笔记17-碎片Fragment(2)
    《第一行代码》学习笔记16-碎片Fragment(1)
    《第一行代码》学习笔记15-UI(4)
    《第一行代码》学习笔记14-UI(3)
    《第一行代码》学习笔记13-UI(2)
    《第一行代码》学习笔记12-UI(1)
    ios-NSMutableAttributedString 更改文本字符串颜色、大小
    ios-实现项目在开发、测试、正式环境快速部署
    ios-滚动导航条页面
  • 原文地址:https://www.cnblogs.com/reboot329/p/6291623.html
Copyright © 2020-2023  润新知