Rectangle Area
Description
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.
Example:
Input: A = -3, B = 0, C = 3, D = 4, E = 0, F = -1, G = 9, H = 2 Output: 45
Note:
Assume that the total area is never beyond the maximum possible value of int.
Solution(javascript)
/*
* @lc app=leetcode id=223 lang=javascript
*
* [223] Rectangle Area
*/
// @lc code=start
/**
* @param {number} A
* @param {number} B
* @param {number} C
* @param {number} D
* @param {number} E
* @param {number} F
* @param {number} G
* @param {number} H
* @return {number}
*/
const computeArea = function (A, B, C, D, E, F, G, H) {
const area = (pointA, pointB) => (pointB[0] - pointA[0]) * (pointB[1] - pointA[1])
const totalArea = area([A, B], [C, D]) + area([E, F], [G, H])
if (E >= C || G <= A || F >= D || H <= B) {
return totalArea
}
const pointA = [Math.max(A, E), Math.max(B, F)]
const pointB = [Math.min(C, G), Math.min(D, H)]
const overlapping = (pointB[0] - pointA[0]) * (pointB[1] - pointA[1])
return totalArea - overlapping
}