Problem Description
Explanation
To find the total area covered by two rectangles, we can first calculate the area of each rectangle separately using the formula: area = (x2 - x1) * (y2 - y1)
. Then, we need to find the overlapping area of the two rectangles. The overlapping area can be calculated by finding the intersection of the x and y ranges of the two rectangles. If the rectangles do not overlap, the overlapping area will be 0. Finally, we add the areas of the two rectangles and subtract the overlapping area to get the total area covered by the two rectangles.
Solutions
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int areaA = (ax2 - ax1) * (ay2 - ay1);
int areaB = (bx2 - bx1) * (by2 - by1);
int overlapWidth = Math.min(ax2, bx2) - Math.max(ax1, bx1);
int overlapHeight = Math.min(ay2, by2) - Math.max(ay1, by1);
int overlapArea = Math.max(overlapWidth, 0) * Math.max(overlapHeight, 0);
return areaA + areaB - overlapArea;
}
}
Related LeetCode Problems
Loading editor...