我们给出了一个(轴对齐的)二维矩形列表 rectangles 。 对于 rectangle[i] = [x1, y1, x2, y2],其中(x1,y1)是矩形 i 左下角的坐标, (xi1, yi1) 是该矩形 左下角 的坐标, (xi2, yi2) 是该矩形 右上角 的坐标。
计算平面中所有 rectangles 所覆盖的 总面积 。任何被两个或多个矩形覆盖的区域应只计算 一次 。返回 总面积 。因为答案可能太大,返回 10^9 + 7 的 模 。

我的第一反应是计算所有矩形面积,然后减去两两相交的面积。这种做法是错误的因为每个重叠部分只要减去一次,可能会重复减去。
这道题的正确思路是把整个区域按所有矩形的边界进行划分,然后逐个计算分块的面积。
步骤:
- class Solution {
- public:
- int rectangleArea(vector
int >>& rectangles) { - long res=0;int i,j,k;
- vector<int> xbound;vector<int> ybound;
- for(i=0;i
size();i++) - {
- xbound.push_back(rectangles[i][0]);
- xbound.push_back(rectangles[i][2]);
- ybound.push_back(rectangles[i][1]);
- ybound.push_back(rectangles[i][3]);
- }
- xbound.erase(unique(xbound.begin(),xbound.end()),xbound.end());
- ybound.erase(unique(ybound.begin(),ybound.end()),ybound.end());
- sort(xbound.begin(),xbound.end());
- sort(ybound.begin(),ybound.end());
- sort(rectangles.begin(),rectangles.end());
- int NumOfLine=ybound.size()-1;
- long area[NumOfLine];
- fill(area,area+NumOfLine,0);
- vector
int>> lines; - for(i=0;i
size();i++) - {
- vector<int> temp;
- j=0;k=ybound.size()-1;
- while(ybound[j]
1]) - j++;
- while(ybound[k]>rectangles[i][3])
- k--;
- while(j
- temp.push_back(j++);
- lines.push_back(temp);
- }
- bool flag[NumOfLine];
- for(i=0;i
size()-1;i++)//i表示扫描线 - {
- fill(flag,flag+NumOfLine,false);
- for(j=0;j
size();j++)//j标记矩形 - {
- if(rectangles[j][0]>xbound[i])
- break;
- if(rectangles[j][2]<=xbound[i])
- continue;
- for(int y:lines[j])
- if(!flag[y])
- {
- area[y]+=(long)(xbound[i+1]-xbound[i])*(ybound[y+1]-ybound[y]);
- flag[y]=true;
- }
- }/**/
- }
- for(i=0;i
- res+=area[i];
- return res%1000000007;
- }
- };
-
相关阅读:
vue 树状结构数据渲染 (java 处理 list ->树状)
机器学习之KNN算法
RTOS任务间通信为什么不用全局变量?
【Git】常见工作场景
【C++】搜索二叉树/KVL树
C语言实现通讯录(超详细)
基于JAVA上虞烟草物流配送系统计算机毕业设计源码+数据库+lw文档+系统+部署
贪心算法篇——区间问题
基于AT89C51单片机的数字电压表PROTEUS仿真设计
【OpenCV4】拉普拉斯算子提取边缘 cv::Laplacian() 用法详解和代码示例(c++)
-
原文地址:https://blog.csdn.net/qq_43533956/article/details/126911288