[Leetcode] 223. Rectangle Area 解题报告
来源:互联网 发布:淘宝女装平铺拍摄技巧 编辑:程序博客网 时间:2024/05/09 09:08
题目:
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、自己的代码:
class Solution {public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area1 = (C - A) * (D - B); int area2 = (G - E) * (H - F); if (E >= C || G <= A || H <= B || F >= D) { // no overlap return area1 + area2; } int width = 0, height = 0; if (E < A) { // update width width = G < C ? (G - A) : (C - A); } else { width = G < C ? (G - E) : (C - E); } if (F < B) { // update height height = H < D ? (H - B) : (D - B); } else { height = H < D ? (H - F) : (D - F); } return area1 + area2 - width * height; }};
2、别人的代码:
class Solution {public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int area = (C - A) * (D - B) + (G - E) * (H - F); if(!(B >= H || F >= D || A >= G ||E >= C)) { int tem = (min(C, G) - max(A, E)) * (min(D, H) -max(B, F)); area -= tem; } return area; }};
class Solution {public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int left = max(A, E), right = max(min(C, G), left); int bot = max(B, F), top = max(min(D, H), bot); return (C - A) * (D - B) + (G - E) * (H - F) - (right - left) * (top - bot); }};
阅读全文
0 0
- [leetcode] 223. Rectangle Area 解题报告
- [Leetcode] 223. Rectangle Area 解题报告
- LeetCode-Rectangle Area 解题报告
- LeetCode---Rectangle Area解题分析
- [leetcode] 223.Rectangle Area
- [leetcode] 223. Rectangle Area
- 223. Rectangle Area LeetCode
- #leetcode# 223. Rectangle Area
- leetcode 223. Rectangle Area
- LeetCode--223. Rectangle Area
- LeetCode *** 223. Rectangle Area
- LeetCode 223. Rectangle Area
- leetcode-223. Rectangle Area
- LeetCode-223.Rectangle Area
- 223.[Leetcode]Rectangle Area
- leetcode 223. Rectangle Area
- 【leetcode】223. Rectangle Area
- [Leetcode]223. Rectangle Area
- 实践---Quartz
- 委托、Lambda表达式和事件
- Kotlin实战01 — Kotlin是什么和为什么
- 空间数据库Spatial Tools的使用
- 技术博客
- [Leetcode] 223. Rectangle Area 解题报告
- Android studio 获取 MD5 和 SHA1
- 二叉查找树练习代码
- Linux mysql结构及数据导出导入
- 备份还原数据库命令
- utf8 utf-8 gbk gb2312的区别
- 嵌入式系统开发前景
- React Navigation基础使用
- python高级编程推荐的好博客