当前位置:网站首页>leetCode-223: 矩形面积
leetCode-223: 矩形面积
2022-06-24 09:43:00 【文丑颜不良啊】
题目描述
给你二维 面上两个由直线构成且边与坐标轴平行/垂直的矩形,请你计算并返回两个矩形覆盖的总面积。
每个矩形由其左下顶点和右上顶点坐标表示:
第一个矩形由其左下顶点 (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
解题过程
思路及步骤
(1)一般思路,先计算两个矩形的面积,再根据是否有重叠去判断是否需要减去重叠部分的面积;
(2)如果有重叠,则需要计算重叠部分的各个坐标。
代码展示
public class ComputeArea {
public int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int area1 = (ax2 - ax1) * (ay2 - ay1);
int area2 = (bx2 - bx1) * (by2 - by1);
if (bx1 >= ax2 || by1 >= ay2 || bx2 <= ax1 || by2 <= ay1) {
// 无重叠
return area1 + area2;
}
int ax1_ = Math.max(ax1, bx1);
int ay1_ = Math.max(ay1, by1);
int ax2_ = Math.min(ax2, bx2);
int ay2_ = Math.min(ay2, by2);
int area3 = (ax2_ - ax1_) * (ay2_ - ay1_);
return area1 + area2 - area3;
}
public static void main(String[] args) {
System.out.println(new ComputeArea().computeArea(-3,0,3,4,0,-1,9,2));
}
}
边栏推荐
- canvas无限扫描js特效代码
- Phpstrom code formatting settings
- Is there a reliable and low commission futures account opening channel in China? Is it safe to open an account online?
- 美国电子烟巨头 Juul 遭遇灭顶之灾,所有产品强制下架
- 记录一下MySql update会锁定哪些范围的数据
- 学习使用KindEditor富文本编辑器,点击上传图片遮罩太大或白屏解决方案
- PHP uses recursive and non recursive methods to create multi-level folders
- 简单的价格表样式代码
- 微信小程序rich-text图片宽高自适应的方法介绍(rich-text富文本)
- 时尚的弹出模态登录注册窗口
猜你喜欢

SQL Sever中的窗口函数row_number()rank()dense_rank()

Arbre binaire partie 1

How to manage massive network infrastructure?

SQL Server AVG function rounding

自定义kindeditor编辑器的工具栏,items即去除不必要的工具栏或者保留部分工具栏

正规方程、、、

Indexeddb local storage, homepage optimization

6.套餐管理业务开发

oracle池式连接请求超时问题排查步骤

Top issue tpami 2022! Behavior recognition based on different data modes: a recent review
随机推荐
416-二叉树(前中后序遍历—迭代法)
3.员工的增删改查
js单例模式
二叉树第一部分
leetCode-1089: 复写零
Is there a reliable and low commission futures account opening channel in China? Is it safe to open an account online?
Operator details
413-二叉树基础
Phpstrom code formatting settings
被困英西中学的师生安全和食物有保障
2022-06-23:给定一个非负数组,任意选择数字,使累加和最大且为7的倍数,返回最大累加和。 n比较大,10的5次方。 来自美团。3.26笔试。
leetCode-498: 对角线遍历
The great charm of cookies
Producer / consumer model
canvas掉落的小球重力js特效动画
4.分类管理业务开发
Arbre binaire partie 1
JS singleton mode
Jcim | AI based protein structure prediction in drug discovery: impacts and challenges
正规方程、、、
输入:ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2