LeetCode_容斥原理_中等_223.矩形面积
2023-09-27 14:25:46 时间
1.题目
给你二维平面上两个由直线构成且边与坐标轴平行/垂直的矩形,请你计算并返回两个矩形覆盖的总面积。
每个矩形由其左下顶点和右上顶点坐标表示:
第一个矩形由其左下顶点 (ax1, ay1) 和右上顶点 (ax2, ay2) 定义。
第二个矩形由其左下顶点 (bx1, by1) 和右上顶点 (bx2, by2) 定义。
示例 1:
输入:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
输出:45
示例 2:
输入:ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
输出:16
提示:
-104 <= ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 <= 104
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rectangle-area
2.思路
(1)容斥原理
通过 2 个集合的容斥原理:A ∪ B = A + B - A ∩ B 可知,两个矩形覆盖的总面积 = 两个矩形的面积之和 - 重合部分的面积,所以我们只需要分别两个矩形的面积以及它们重合部分的面积即可,需要注意的是两个矩形可能不重合,即重合部分的面积为 0。
3.代码实现(Java)
//思路1————容斥原理
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
// 矩形 A 的面积
int areaA = (ax2 - ax1) * (ay2 - ay1);
// 矩形 B 的面积
int areaB = (bx2 - bx1) * (by2 - by1);
int x = Math.max(0, Math.min(ax2, bx2) - Math.max(ax1, bx1));
int y = Math.max(0, Math.min(ay2, by2) - Math.max(ay1, by1));
// 矩形 A 和矩形 B 重合部分的面积(可能为 0)
int coincide = x * y;
/*
2 个集合的容斥原理:A ∪ B = A + B - A ∩ B
两个矩形覆盖的总面积 = 两个矩形的面积之和 - 重合部分的面积
*/
return areaA + areaB - coincide;
}
}
相关文章
- Leetcode: Intersection of Two Arrays
- Leetcode: Factor Combinations
- 【算法/贪心】leetcode刷题路线(持续更新)
- 【LeetCode】Longest Substring with At Most Two Distinct Characters (2 solutions)
- Leetcode--easy系列1
- [LeetCode] 1055. Shortest Way to Form String 形成字符串的最短方法
- [LeetCode] 1157. Online Majority Element In Subarray 子数组中占绝大多数的元素
- [LeetCode] Search in a Sorted Array of Unknown Size 在未知大小的有序数组中搜索
- [LeetCode] 444. Sequence Reconstruction 序列重建
- [LeetCode] 375. Guess Number Higher or Lower II 猜数字大小之二
- [LeetCode] 296. Best Meeting Point 最佳开会地点
- leetcode算法226.翻转二叉树