zoukankan      html  css  js  c++  java
  • 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.

    看到这道题的时候,我觉得有些难,我一点思路也没有,没怎么解过这种类型的题目,甚至对于题意也理解错了(以为是计算重合的面积)

    这道题如果突破几个点的话就很简单了。因为我以为是要计算重合的面积,而这道题也必须计算重合的面积,就先讲重合面积怎么算吧,

    最后的结果就是S(A)+S(B)-S(A∩B)

    计算A∩B:

    因为矩形的面积说到底是长*宽,所以我们要找到计算重合的长和宽。这里我用一个函数来独立实现。

    1.计算两条线的重合宽度,需要参数四个来分别表示两条线的位置。根据这个四个点的位置以及其关系,利用数学思维(注意分析很多种情况),就可以得到重合的长度。(本来我以为分别要为XY坐标写一个函数,事实上写一个就可以了,XY坐标是同理的)

    2.既然得到重合的长和宽乘起来就是面积啦

    后面的没有什么难度了,就不赘述啦。

     1 class Solution {
     2 public:
     3 
     4     int getLine(int a,int b,int c,int d){
     5         if(b<=c) return 0;
     6         if(b>c&&b<d){
     7             if(a<=c) return b-c;
     8             if(a>c) return b-a;
     9             
    10         }
    11         if(b>=d){
    12             if(a<=d) {
    13                 if(a>c) return d-a;
    14                 else return d-c;
    15             }
    16             if(a>d) return 0;
    17         }
    18     }
    19     int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    20         int xs1=min(A,C),xb1=max(A,C),ys1=min(B,D),yb1=max(B,D);
    21         int xs2=min(E,G),xb2=max(E,G),ys2=min(F,H),yb2=max(F,H);
    22         int result=(xb1-xs1)*(yb1-ys1)+(xb2-xs2)*(yb2-ys2);
    23         return result-getLine(xs1,xb1,xs2,xb2)*getLine(ys1,yb1,ys2,yb2);
    24         
    25     }
    26 };
  • 相关阅读:
    堆、栈及静态数据区详解
    新浪云上传代码包
    主机屋MySQL数据库链接
    Doctype作用?严格模式与混杂模式如何区分?它们有何意义?
    height 与 min-height 的继承
    @media 照成的问题
    img 在chrome和Firefox下的兼容性
    Ionic
    setInterval()和setTimeout()可以接收更多的参数
    angularJs 模拟jQuery中的this
  • 原文地址:https://www.cnblogs.com/LUO77/p/5043681.html
Copyright © 2011-2022 走看看