我们给出了一个(轴对齐的)二维矩形列表 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;
- }
- };
-
相关阅读:
2022年9月2日:面向初学者的 web 开发--使用 JavaScript 制定决策
Rust 技术文档及详细使用命令
Arduino ESP8266/32 自定义IO组网页状态显示与控制
基于Qt实现的可视化大屏监控
运维排查 | Systemd 之服务停止后状态为 failed
牛客网项目-开发注册功能
蓝牙资讯|三星推迟发布智能戒指Galaxy Ring,智能穿戴小型化是大趋势
CSMACD协议与CSMACA协议
保研后,你们都怎么样了?
孕妇胃烧心是胎儿长头发?其实是因为这2点
-
原文地址:https://blog.csdn.net/qq_43533956/article/details/126911288