Leetcode 223 Rectangle Area
来源:互联网 发布:淘宝打假团队招聘 编辑:程序博客网 时间:2024/06/05 15:24
题目:
题目的意思大概就是给你四个坐标,来表示两个矩形。然后计算两个矩形的面积,这里都是假设两个矩形都是水平的。
解题思路: 这个问题其实可以分成一个更小的问题,就是给你一个数轴上两条线段(四个点设线段L1(x1,x2), 线段L2(y1,y2)),要你求解他们重合的长度。他们在数轴上的分布情况可以分为以下三种情况。
1、两个线段没有相交的情况,即y2≤x1或者y1≥x2
2、某条线段在另外一条线段的内部,即(y1≥x1&&y2≤x2)||(x1≥y1&&x2≤y2)
3、两条线段部分相交,即(y1≤x1&&y2≥x1&&y2≤x2)||(y1≥x1&&y1≤x2&&y2≥x2)
根据这样的两种情况,就可以把重合部分矩形的长和宽计算出来。就可以做出来了,代码如下。
int dealt(int x1,int x2,int y1,int y2) { if(y1>=x2||y2<=x1) return 0; if(x1<=y1&&y2<=x2) return y2-y1; if(y1<=x1&&x2<=y2) return x2-x1; if(y1<=x1&&y2>=x1&&y2<=x2) return y2-x1; if(y1>=x1&&y1<=x2&&y2>=x2) return x2-y1; } int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { return (C-A)*(D-B)+(G-E)*(H-F)-dealt(A,C,E,G)*dealt(B,D,F,H); }
在求解这种重合的情况,当线段相对比较多的时候,就不应该使用这种分类讨论的情况,先对其排序再求解,具体可以参考soj上的“校园里的树”一题。这里也可以使用排序的方法,代码如下。
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) { int ans=(D-B)*(C-A)+(G-E)*(H-F); if(E>=C||G<=A||F>=D||H<=B) return ans; else { vector<int> x; x.push_back(A); x.push_back(C); x.push_back(E); x.push_back(G); vector<int> y; y.push_back(B); y.push_back(D); y.push_back(F); y.push_back(H); sort(x.begin(),x.end()); sort(y.begin(),y.end()); return ans-((x[2]-x[1])*(y[2]-y[1])); } return ans; }
总结: 虽然说排序是一种更为科学的方法,但是在这里它只有两条线段,使用排序还要开两个vector还要排序,那空间和时间复杂度是不是相对而言比较高一点?
0 0
- 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
- 【leetcode】【223】Rectangle Area
- MySQL---数据库从入门走向大神系列--基础入门
- 3.6 XNA数学库中的转换函数
- asp.net core mvc剖析:mvc动作选择
- MySQL 表自连接 出现 Column 'ename' in field list is ambiguous
- TCL 雏鹰飞翔计划 Android篇
- Leetcode 223 Rectangle Area
- Quartz调度器开发指南
- java.lang.NoClassDefFoundError: org/apache/commons/lang/StringUtils
- LeetCode 35. Search Insert Position
- hbase学习
- mybatis+springmvc:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
- mysql之锁表机制与死锁浅谈
- linux命令(三)
- 【Unity&加密】DLL加密文章说明