关于LeetCode中Rectangle Area一题的理解

题目如下:

Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Rectangle Area

Assume that the total area is never beyond the maximum possible value of int.

    题目的要求是求两个长方形覆盖区域的总面积,基本思想是把两个长方形的面积先求出来,然后相加,最后再减去重合部分的面积,思路非常简单,然后要注意题干中“Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.”这句话,这句话是说正方形的是按照它的左下角和右上角进行定义的,所以不需要担心H是不是可能比F要小或者G是不是要比E要小这种问题,人家已经定义好了,我就没看见,所以白白多写了好些比较大小的代码,不说了,都是泪,代码如下:

    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int right1 = Math.max(E,G);
        int left1 = Math.min(E,G);
        
        int right2 = Math.max(A,C);
        int left2 = Math.min(A,C);
        
        int top1 = Math.max(H,F);
        int bottom1 = Math.min(H,F);
        
        int top2 = Math.max(B,D);
        int bottom2 = Math.min(B,D);
        
        int area1 = (right1-left1)*(top1-bottom1);
        int area2 = (right2-left2)*(top2-bottom2);
        
        if(right1<=left2 || right2<=left1 || top1<=bottom2 || top2<=bottom1 ){
            return area1+area2;
        }
        
        int left = Math.max(left1,left2);
        int right = Math.min(right1,right2);
        int top = Math.min(top1,top2);
        int bottom = Math.max(bottom1,bottom2);
        
        return area1+area2-(right-left)*(top-bottom);
    }
    然后是评论区写的比较好的代码,如下所示,思路一样的,就是人家认真审题了:

public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        
        int areaOfSqrA = (C-A) * (D-B);
         int areaOfSqrB = (G-E) * (H-F);
        
        int left = Math.max(A, E);
        int right = Math.min(G, C);
        int bottom = Math.max(F, B);
        int top = Math.min(D, H);
        
        //If overlap
        int overlap = 0;
        if(right > left && top > bottom)
             overlap = (right - left) * (top - bottom);
        
        return areaOfSqrA + areaOfSqrB - overlap;
    }
    最后是评论区有位“patient guy”的代码,这里就不贴了,大家自己感受下什么叫有毅力,标题也非常醒目,我给满分,这个代码的地址在这里: https://discuss.leetcode.com/topic/17534/if-you-want-to-laugh-look-at-my-solution

    大家以后也要注意审题呦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值