LeetCode 850. 矩形面积 II
离散化 + 二维差分
const int N = 210, MOD = 1e9 + 7;
typedef long long LL;
class Solution {
public:
int b[N][N] = {0};
void insert(int x1, int y1, int x2, int y2, int c)
{
b[x1][y1] += c;
b[x2 + 1][y1] -= c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y2 + 1] += c;
}
void sum(int n, int m)
{
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= m; j ++)
{
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1]; //错过好多次了
}
}
int rectangleArea(vector<vector<int>>& rectangles) {
set<int> pointx, pointy;
pointx.insert(-1);
pointy.insert(-1); //讲点的下标和数组下标对应成1开始
for(auto&& r : rectangles)
{
pointx.insert(r[0]);
pointx.insert(r[2]);
pointy.insert(r[1]);
pointy.insert(r[3]);
}
vector<int> xs(pointx.begin(), pointx.end());
vector<int> ys(pointy.begin(), pointy.end());
unordered_map<int, int> x2i, y2i;
for(int i = 1; i < xs.size(); i ++)
x2i[xs[i]] = i;
for(int i = 1; i < ys.size(); i ++)
y2i[ys[i]] = i; // 离散化
for(auto&& r : rectangles)
{
int x1 = x2i[r[0]];
int y1 = y2i[r[1]];
int x2 = x2i[r[2]] - 1;
int y2 = y2i[r[3]] - 1; //只是将范围内的 + 1
insert(x1, y1, x2, y2, 1);
}
sum(xs.size(), ys.size());
LL res = 0;
for(int i = 1; i <= xs.size(); i ++)
for(int j = 1; j <= xs.size(); j ++)
{
// cout <<i << " " << j << " "<< b[i][j] << endl;
if(b[i][j] > 0)
{
LL dx = xs[i + 1] - xs[i];
LL dy = ys[j + 1] - ys[j];
res = (res + dx * dy % MOD) % MOD;
}
}
return res;
}
};