leetcode 223 Retangle Area
来源:互联网 发布:sql2000自动备份数据库 编辑:程序博客网 时间:2024/05/16 06:44
题目要求:求两个长方形的总面积(长方形长和x周平行,宽和y轴平行)
tags:math
思路:求重合边的长度,然后求得重合面积。总面积为两个长方形的面积和减去重合面积。
我的代码:
情况1:如果长方形有一对边是分离的,则两个长方形不相交
情况2:如果长方形有一对边是包含的,则短边乘以另一对边相交长度,则为重合面积
情况3:两对边都是包含一部分,则重合面积为两边相交长度乘机
由上分析可得,3种情况可以合并成为计算每对边交合长度来计算其重合面积。
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {int mutualACEG = 0; if(A>E){//E在A左边 if(A>G){//G在A左边 mutualACEG = 0; }else if(A<=G&&C>=G){//G在AC中间 mutualACEG = G-A; }else{//G在C左边 mutualACEG = C-A; } }else if(A<=E&&C>=E){//E在AC中间 if(A<=G&&C>=G){//G在AC中间 mutualACEG = G-E; }else{//G在C右边 mutualACEG = C-E; } }else{//E在C右边 mutualACEG = 0; } int mutualBDFH = 0; if(B>F){//F在B下边 if(B>H){//H在B下边 mutualBDFH = 0; }else if(B<=H&&D>=H){//H在BD中间 mutualBDFH = H-B; }else{//H在D上边 mutualBDFH = D-B; } }else if(B<=F&&D>=F){//F在BD中间 if(B<=H&&D>=H){//H在BD中间 mutualBDFH = H-F; }else{//H在D上边 mutualBDFH = D-F; } }else{//F在D上边 mutualBDFH = 0; } return (C-A)*(D-B)+(G-E)*(H-F)-mutualACEG*mutualBDFH; }
//别人的思路,只需要知道小的点的最大点,和大的点的最小点,即可获得共同长度//由于两个长方形不分先后,所以可以通过比大小来操作public int computeArea2(int A, int B, int C, int D, int E, int F, int G, int H) {int left = Math.max(A,C);int right = Math.max(Math.min(C, G),left);int bottom = Math.max(B, F);int top = Math.max(Math.min(D,H), bottom); return (C-A)*(D-B)+(G-E)*(H-F)-(right-left)*(top-bottom); }
0 0
- leetcode 223 Retangle Area
- Rectangle Area - LeetCode 223
- 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
- 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
- leetcode 223: Rectangle Area
- leetcode 223: Rectangle Area
- Java 读取属性文件Properties,方式2
- 前端提交的中文数据与后端数据库无法正确匹配的问题
- C++指针和数组:认识指针和数组
- 九度OJ 1174:查找第K小数 (排序、查找)
- 理解dropout
- leetcode 223 Retangle Area
- svn分支
- 《从零开始学Swift》学习笔记(Day 27)——可选类型
- arm-linux-gcc( arm-none-linux-gnueabi-gcc) cause "No such file or directory"
- 免安装版MySQL的配置
- C_运算符优先级
- 苹果开发 所要知道的那些类库含义 Cocoa,Foundation,UIKit,Objective-C,Xcode,Interface Builder,
- 互联网面试题之趣味数学题
- JAVA集合框架概述