[leetcode 223] Rectangle Area
2015-11-19 12:33
417 查看
Question:
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.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.
分析:
暴力法:
最简单的情况就是排除几个特例情况,然后分析有重叠的情况。两种情况,有重叠,无重叠。
无重叠:横坐或是纵坐标没有交集。直接返回两个矩形的面积。
有重叠:对四个横坐标和四个纵坐标排序,横坐标中间的两个数的差值就是重叠部分的宽,纵坐标中间的两个数的差值就是重叠部分的高。
结果即为两个矩形面积和再减去重叠部分的面积。
不用排序的方法:
暴力法也可以解决问题,可以通过leetcode的测试,但是运行时间过长,如果不采用排序的方法:
第一步也是先把无重叠的部分优先判断;
第二步有重叠包含两种情况:
部分重叠;
其中一个矩阵完全重叠在另一个矩阵中。
重叠部分的宽 则 取自身宽度差 和 与另一个矩阵宽度差 的最小值,这样就包含了完全重叠的情况。
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.
Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.
分析:
暴力法:
最简单的情况就是排除几个特例情况,然后分析有重叠的情况。两种情况,有重叠,无重叠。
无重叠:横坐或是纵坐标没有交集。直接返回两个矩形的面积。
有重叠:对四个横坐标和四个纵坐标排序,横坐标中间的两个数的差值就是重叠部分的宽,纵坐标中间的两个数的差值就是重叠部分的高。
结果即为两个矩形面积和再减去重叠部分的面积。
不用排序的方法:
暴力法也可以解决问题,可以通过leetcode的测试,但是运行时间过长,如果不采用排序的方法:
第一步也是先把无重叠的部分优先判断;
第二步有重叠包含两种情况:
部分重叠;
其中一个矩阵完全重叠在另一个矩阵中。
重叠部分的宽 则 取自身宽度差 和 与另一个矩阵宽度差 的最小值,这样就包含了完全重叠的情况。
<span style="font-size:14px;">class Solution { private: int area(int height, int width){ return height*width; } public: int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { /*int result; int area1,area2,area3; area1 = area(D-B,C-A); area2 = area(H-F,G-E); if(E < A && F < B && G > C && H > D) return area2; if(A < E && B < F && C > G && D > H) return area1; if(A == E && B == F && C == G && D == H) return area1; if(C < E || G < A || F > D || H < B) return area1+area2; vector<int> Xsort{A,C,E,G}; vector<int> Ysort{B,D,F,H}; sort(Xsort.begin(),Xsort.end()); sort(Ysort.begin(),Ysort.end()); area3 = area(Ysort[2]-Ysort[1], Xsort[2]-Xsort[1]); return area1 + area2 - area3;*/ int area1 = (C-A)*(D-B); int area2 = (G-E)*(H-F); if(C<=E || G<=A || D<=F ||B>=H){ return area1+area2; } int width = (A<=E)?min(C-E,G-E):min(C-A,G-A); int height = (B>=F)?min(D-B,H-B):min(D-F,H-F); return area1+area2-width*height; } };</span>
相关文章推荐
- 配置MySQL远程访问权限
- dom事件
- android 四大组件service 音乐播放器的实现
- QtCreator下复制文件夹的一个BUG
- 运算符
- Centos平台Supervisord全攻略
- 希尔排序c语言版
- HashMap vs. TreeMap vs. Hashtable vs. LinkedHashMap
- 输入子系统
- 实验二固件设计报告
- 回归
- Hadoop安装简单版本
- 数据挖掘与机器学习的区别
- CodeForces 540B School Marks
- Luc Berson's letter
- java编程实现根据EXCEL列名求其索引的方法
- 移动端6种导航设计总结
- C# 设计模式----抽象工厂模式
- Merge Sorted Array
- C# 设计模式----抽象工厂模式