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

    对于这个问题,如果思路正确,解决起来还是比较简单的。

    1.如果没有重叠,则直接返回两个矩形的总面积:(C-A)*(D-B) + (G-E)*(H-F)。判断两个矩形是否重叠:if(C<E || G<A || H<B || D<F)。

    2.如果有重叠,计算重叠面积的大小。总面积-重叠面积。

     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         int total = (C-A)*(D-B) + (G-E)*(H-F);
     4         if(B>H || C<E || D<F || A>G) return total;
     5         int l = 0;
     6         if(E>A) l = Math.min((C-E),(G-E));
     7         else l = Math.min((C-A),(G-A));
     8         int h = 0;
     9         if(D>H) h = Math.min((H-B),(H-F));
    10         else h = Math.min((D-B),(D-F));
    11         return (total-(l*h));
    12     }
    13 }

    计算重叠部分的长和宽是一个难点,要明确可能重叠的几种情况,然后用简洁的代码把它表示出来。

  • 相关阅读:
    设置网络
    href
    webpack学习
    那些个像素
    jquery Id选择器与document.getElementByIdy区别
    又一个很垃圾的设计
    卸载QQ,360,迅雷,搜狗
    CheckFail设计很垃圾
    js写法【2】
    require的定义看不懂【2】
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5374964.html
Copyright © 2011-2022 走看看