223. Rectangle Area
給定在二維平面上兩個直角矩形的座標,返回這兩個矩形覆蓋的總面積。
第一個矩形由其左下角 (ax1, ay1) 和右上角 (ax2, ay2) 定義。
第二個矩形由其左下角 (bx1, by1) 和右上角 (bx2, by2) 定義。
範例
Python
class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
# Calculate areas of both rectangles
area1 = (ax2 - ax1) * (ay2 - ay1)
area2 = (bx2 - bx1) * (by2 - by1)
# Find the overlapping region
left = max(ax1, bx1)
right = min(ax2, bx2)
top = min(ay2, by2)
bottom = max(ay1, by1)
# Calculate overlapping area
overlap_area = 0
if left < right and bottom < top:
overlap_area = (right - left) * (top - bottom)
# Total area is sum of both areas minus the overlap
total_area = area1 + area2 - overlap_area
return total_area
16.62MB, 12ms
C++
class Solution {
public:
int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// Calculate areas of both rectangles
long long area1 = static_cast<long long>(ax2 - ax1) * (ay2 - ay1);
long long area2 = static_cast<long long>(bx2 - bx1) * (by2 - by1);
// Find the overlapping region
int left = max(ax1, bx1);
int right = min(ax2, bx2);
int top = min(ay2, by2);
int bottom = max(ay1, by1);
// Calculate overlapping area
long long overlap_area = 0;
if (left < right && bottom < top) {
overlap_area = static_cast<long long>(right - left) * (top - bottom);
}
// Total area is sum of both areas minus the overlap
long long total_area = area1 + area2 - overlap_area;
return static_cast<int>(total_area);
}
};
9.92MB, 0ms
Javascript
/**
* @param {number} ax1
* @param {number} ay1
* @param {number} ax2
* @param {number} ay2
* @param {number} bx1
* @param {number} by1
* @param {number} bx2
* @param {number} by2
* @return {number}
*/
var computeArea = function(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2) {
// Calculate areas of both rectangles
const area1 = (ax2 - ax1) * (ay2 - ay1);
const area2 = (bx2 - bx1) * (by2 - by1);
// Find the overlapping region
const left = Math.max(ax1, bx1);
const right = Math.min(ax2, bx2);
const top = Math.min(ay2, by2);
const bottom = Math.max(ay1, by1);
// Calculate overlapping area
let overlapArea = 0;
if (left < right && bottom < top) {
overlapArea = (right - left) * (top - bottom);
}
// Total area is sum of both areas minus the overlap
const totalArea = area1 + area2 - overlapArea;
return totalArea;
};
55.62MB, 119ms