LeetCode 223. Rectangle Area(两个矩形的复合面积计算)
来源:互联网 发布:php row 编辑:程序博客网 时间:2024/05/16 08:01
原题网址: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.
思路:两个矩形各自的面积之和,减去重叠部分的面积,所以难点是如何计算重叠部分的面积。可以对两个矩形的左边、下边、右边、上边各自比较,例如两个矩形的左边比较,取最大者;两个矩形的右边比较,取最小者,两个矩形的下边比较,取最大者;两个矩形的上边比较,取最小者。
代码:
public class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int sum = (C-A)*(D-B)+(G-E)*(H-F); if (A<E) A=E; else if (E<A) E=A; if (A>=C || E>=G) return sum; if (G>C) G=C; else if (C>G) C=G; if (A>=C || E>=G) return sum; if (B<F) B=F; else if (F<B) F=B; if (B>=D || F>=H) return sum; if (D>H) D=H; else if (H>D) H=D; if (B>=D || F>=H) return sum; return sum-(C-A)*(D-B); }}可以对上面代码进行简化:
public class Solution { public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { return (int)((C-A)*(D-B)+(G-E)*(H-F)-Math.max(0, (long)Math.min(C,G)-Math.max(A,E))*Math.max(0,(long)Math.min(D,H)-Math.max(B,F))); }}
0 0
- LeetCode 223. Rectangle Area(两个矩形的复合面积计算)
- leetcode 223. Rectangle Area 矩形面积计算
- Rectangle Area 两个矩形的面积
- Rectangle Area 两个矩形的面积
- leetcode 223. Rectangle Area-矩形面积
- LeetCode 223 Rectangle Area(矩形面积)
- leetcode_223. Rectangle Area 求两个矩形覆盖的面积之和
- LeetCode-223. Rectangle Area (JAVA)求矩形覆盖面积
- Leetcode 223 Rectangle Area 矩形区域面积
- 223. Rectangle Area (求两矩形重合部分的面积)
- Rectangle Area-带有交差集矩形面积
- (LeetCode)Rectangle Area --- 求图形覆盖的面积
- LeetCode----223. Rectangle Area 2个矩形和
- LeetCode Rectangle Area 简单计算
- [leetcode] 223.Rectangle Area
- [leetcode] 223. Rectangle Area
- 223. Rectangle Area LeetCode
- #leetcode# 223. Rectangle Area
- LeetCode 8 String to Integer (atoi)
- 关于真机测试的android选择图片在ImageView上显示,调用setImageBitmap无法显示和闪退、控件消失
- php模式设计之 注册树模式
- C++作业2
- linux进程调度之总章:一些片汤话
- LeetCode 223. Rectangle Area(两个矩形的复合面积计算)
- leetcode:排序数组之后相邻数的最大差
- install firebox on ubuntu
- Linux的进程调度时机(Schedule函数何时调用)
- mysql创建序列
- 《大型网站技术架构:核心原理与案例分析》
- <<c>>背包问题(Knapsack)
- Nexus创建本地Maven仓库(Maven私服)
- sysbench常用技巧