PU Rectangle Area

Jan 01, 1970

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.

  • Assume that the total area is never beyond the maximum possible value of int.

223. Rectangle Area

C Solution:

int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    int areaA = (C - A) * (D - B);
    int areaE = (G - E) * (H - F);

    if (A >= G || C <= E || B >= H || D <= F) return areaA + areaE;
    int h = (C < G ? C : G) - (A > E ? A : E);
    int v = (D < H ? D : H) - (B > F ? B : F);

    return areaA + areaE - h * v;
}

Summary:

  1. If you don't figure out the logic behide clearly, you could write complex code.
  2. Think first.
  3. 12ms, 7.27%

LeetCode: 223. Rectangle Area