# Leetcode 223 Rectangle Area 矩形区域面积

## 原题地址

https://leetcode.com/problems/rectangle-area/

## 题目描述

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.

## 解题思路

1. 判定重合

• （1）如果矩形A的右上顶点的横坐标小于矩形B的左下角的横坐标
• （2）如果矩形A的左下顶点的横坐标大于矩形B的右上角下角的横坐标
• （3）如果矩形A的左下顶点的纵坐标大于矩形B的右上角的纵坐标
• （4）如果矩形A的右上顶点的纵坐标小于矩形B的左下角的纵坐标

2. 有重合时求重合部分面积

## 代码

/**
* 计算两个矩形覆盖的总面积
*/
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
return (D - B) * (C - A) + (H - F) * (G - E) -
computeRetainArea(A, B, C, D, E, F, G, H);
}

/**
* 计算两个矩形重合区域面积
*/
int computeRetainArea(int A, int B, int C, int D, int E, int F, int G, int H) {
void sort(int*, int, int);
if (E >= C || G <= A || H <= B || F >= D) return 0; // 不重合
int nums[4];
// 计算x坐标重合区域差值
nums[0] = A;
nums[1] = C;
nums[2] = E;
nums[3] = G;
sort(nums, 0, 3);
int diffX = nums[1] - nums[2];
// 计算y坐标重合区域差值
nums[0] = B;
nums[1] = D;
nums[2] = F;
nums[3] = H;
sort(nums, 0, 3);
int diffY = nums[1] - nums[2];

int ans = diffX * diffY;
return ans < 0 ? -ans : ans;
}

## 测试数据

-3,0,3,4,0,-1,9,2 : 45
-2,-2,2,2,-2,-2,2,2 : 16
0,0,0,0,-1,-1,1,1 : 4


2015/8/28

#### LeetCode 223. Rectangle Area（两个矩形的复合面积计算）

2016-04-05 00:48:05

#### LeetCode-223. Rectangle Area (JAVA)求矩形覆盖面积

2017-04-29 22:31:36

#### Leetcode_223_Rectangle Area

2015-07-13 22:02:28

#### 【LeetCode-面试算法经典-Java实现】【223-Rectangle Area（矩形区域）】

2015-08-29 06:39:48

#### leetcode 223: Rectangle Area

2015-06-10 03:25:56

#### 223. Rectangle Area

2016-05-26 19:17:22

#### [LeetCode 223] Rectangle Area

2015-09-24 03:27:17

#### [leetcode-223]Rectangle Area(c++)

2015-08-25 10:09:39

#### Leetcode No.223 Rectangle Area 判断矩形相交

2016-06-13 09:54:14

#### 屏幕坐标系获取两个矩形面积及重叠面积，重叠面积比率的java代码

2016-07-15 17:49:35