LeetCode 223. Rectangle Area



Easy level which probably means easy to make mistakes......

Better to draw a graph to make the question clear..... 


Under these situations, there is no overlap.

LeetCode 223. Rectangle Area_第1张图片

Thus, G <= A || E >= C || G <= B || F >= D.... there is no overlap, the total area is the sum of two cubes area 


For the overlap situation, we just need to consider one situation, all the overlaps will be the same anyway....

The easiest one would be one is totally inside the other one.

LeetCode 223. Rectangle Area_第2张图片

In this case, the overlap area woud be overlap = abs(min(G, C) - max(A, E)) * abs(max(B,  F) - min(D, H));

Thus the total area is The sum of two cubes area - overlap.....

Generate code would be easy then.....

int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
        if(E >= C || G <= A || H <= B || D <= F) return (C-A)*(D-B)+(G-E)*(H-F);
        else {
            return (C-A)*(D-B)+(G-E)*(H-F) - (min(C, G) - max(A, E)) * (min(H, D) - max(B, F));
        }
    }


你可能感兴趣的:(LeetCode 223. Rectangle Area)