zoukankan      html  css  js  c++  java
  • 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;
            }
        }
    }
    
  • 相关阅读:
    C++学习 之 继承(笔记)
    C++学习 之 类中的特殊函数和this指针(笔记)
    C++学习 之 类的声明及成员的访问(笔记)
    C++学习 之 指针及动态内存分配(笔记)
    C++学习 之 函数的重载及内联(笔记)
    C++学习 之 控制程序流程 (笔记)
    pkg-config too old的解决方法
    编译中出现的undefined reference to XXX
    sourceInsight下标题栏显示文件完整路径
    linux下 sleep() 与 usleep()
  • 原文地址:https://www.cnblogs.com/reboot329/p/6291623.html
Copyright © 2011-2022 走看看