Leetcode: Rectangle Area
This question is asked in Zillow, Facebook, and Apple. Here it is:
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by the bottom-left corner (A, B) and top right corner (C, D) and the second rectangle is defined by its bottom left corner (E, F) and top-right corner (G,H).
Here's an example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2
Output: 45
Here's an example diagram:
So what we want to do is we want to add up the areas of both of the rectangles and subtract the intersection between these rectangles.
First, we compute the area of both of the rectangle and we want to calculate the overlap. This means that we calculate the left and right and top and bottom and then (right - left) * (top - bottom). For the left and bottom, we calculate the maximum and the minimum for the top and right. Here is the code:
class Solution {
public int computerArea(int A, int B, int C, int D, int E, int F, int G, int H) {
//calculate the area of each rectangle
int areaOfSqrA = (C - A) * (D - B);
int areaOfSqrB = (G - E) * (H - F);
//calculate the corners of the overlapping triangle.
int left = Math.max(A, E);
int right = Math.min(G, C);
int bottom = Math.max(F, B);
int top = Math.min(D, H);
int overlap = 0;
//area of overlapping triangle
if (right > left && top > bottom) {
overlap = (right - left) * (top - bottom);
}
// take (A ∪ B) - (A ∩ B)
return areaOfSqrA + areaOfSqrB - overlap;
}
}


Comments
Post a Comment