223. Rectangle Area

Question

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. question

Example:

Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45

Thinking:

  • Method 1:两个长方形的面积和 - 交集的面积
class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int total  = (C - A) * (D - B) + (G - E) * (H - F);
        if(E > C || G < A || F > D || H < B) return total;
        else{
            int height = Math.min(H, D) - Math.max(B, F);
            int width = Math.min(G, C) - Math.max(A, E);
            return total - height * width;
        }
    }
}

二刷

  1. 和一刷的想法一样,但是出了一个问题,两个长方形的相对位置是不确定的,所以我们要使用最大值,最小值来解决这个问题。
    class Solution {
     public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
         int total = (D - B) * (C - A) + (H - F)  * (G - E);
         if(E >= C || G <= A || H <= B || F >= D) return total;
         return total - (Math.min(C, G) - Math.max(A, E)) * (Math.min(D, H) - Math.max(F, B));
     }
    }