我们给出了一个(轴对齐的)二维矩形列表 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;
- }
- };
-
相关阅读:
MyBatis:3_增删查改
ansible配置文件介绍
pytorch 模型部署之Libtorch
Flutter 必备知识点
在云服务器上安装配置和调优Zerotier服务器的详细教程
Web安全专业学习路线
基于单片机的推箱子游戏仿真设计(#0014)
如何为WPF应用程序制作一个虚拟键盘?这里有答案(Part 1)
【编程题】【Scratch一级】2022.06 报时的公鸡
JavaEE-多线程之进程的调度
-
原文地址:https://blog.csdn.net/qq_43533956/article/details/126911288