223. Rectangle Area

一、题目

  1、审题

  

  2、分析

    给出二维空间中两个矩形的坐标,求这两个矩阵的总面积。(注意重叠部分)

 

二、解答

  1、思路

    首先计算两个矩阵s1, s2 的面积,在计算重叠部分的面积。

    重叠部分,可能是 s1 与 s2 的包含关系,或者部分包含、或者矩阵 s1 为一个点。

 1     public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
 2         
 3         int areaOfSqrA = (C-A) * (D-B);
 4         int areaOfSqrB = (G-E) * (H-F);
 5        
 6         int left = Math.max(A, E);
 7         int right = Math.min(G, C);
 8         int bottom = Math.max(F, B);
 9         int top = Math.min(D, H);
10        
11         //If overlap
12         int overlap = 0;
13         if(right > left && top > bottom)
14             overlap = (right - left) * (top - bottom);
15        
16         return areaOfSqrA + areaOfSqrB - overlap;
17     }

 

posted @ 2018-11-05 16:44  skillking2  阅读(95)  评论(0编辑  收藏  举报