LeetCode--223. Rectangle Area

客官°小女子只卖身不卖艺 2022-07-27 13:38 256阅读 0赞

Problem:

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

Credits:
Special thanks to @mithmatt for adding this problem, creating the above image and all test cases.

Answer:

  1. public class Solution {
  2. public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
  3. //计算分离的两块长方形面积area1和area2
  4. int area1 = Math.abs((C-A)*(D-B));
  5. int area2 = Math.abs((E-G)*(F-H));
  6. if(B>H || D<F || C<E || A>G) return area1+area2;
  7. //确定叠加区域的两个X和两个Y
  8. int maxX = Math.min(C,G);
  9. int minX = Math.max(A,E);
  10. int maxY = Math.min(D,H);
  11. int minY = Math.max(B,F);
  12. //计算叠加区域面积
  13. int area = (maxX-minX)*(maxY-minY);
  14. return area1+area2-area;
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,256人围观)

还没有评论,来说两句吧...

相关阅读