Leetcode - Rectangle Area

My code:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
         int area = (D - B) * (C - A) + (H - F) * (G - E);
         if (A >= G || B >= H || C <= E || D <= F)
         {
             return area;
         }

         int top = Math.min(D, H);
         int right = Math.min(C, G);
         int bottom = Math.max(B, F);
         int left = Math.max(A, E);

         return area - (top - bottom) * (right - left);
    }
}

没有任何意思的题目。。。虽然我没有做出来。
先判断两个矩形是否会相交,不会的话就返回总面积。
会的话,就减去重复的,再返回。

**
总结: Math
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int area1 = (D - B) * (C - A);
        int area2 = (H - F) * (G - E);
        int overlap = 0;
        int left = Math.max(A, E);
        int right = Math.min(C, G);
        int bottom = Math.max(B, F);
        int top = Math.min(D, H);
        
        if (right > left && top > bottom) {
            overlap = (right - left) * (top - bottom);
        }
        
        return area1 + area2 - overlap;
    }
}

reference:
https://discuss.leetcode.com/topic/15733/my-java-solution-sum-of-areas-overlapped-area

Anyway, Good luck, Richardo! — 10/12/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/9b5e8657ab19#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞