223. Rectangle Area (Easy)

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.

Solution:

public class Solution {
    public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        int sum = (C-A)*(D-B)+(G-E)*(H-F);
        // check overlap
        if (E >= C || G <= A || H <= B || F >= D) return sum;
        return sum-(Math.min(C,G)-Math.max(A,E))*(Math.min(D,H)-Math.max(B,F));
    }
}
class Solution {
public:
    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        return (C - A) * (D - B) + (H - F) * (G - E) - (max((min(G, C) - max(A, E)), 0) * max((min(D, H) - max(B, F)), 0));
    }
};

results matching ""

    No results matching ""