我们给出了一个(轴对齐的)矩形列表 rectangles 。 对于 rectangle[i] = [x1, y1, x2, y2],其中(x1,y1)是矩形 i 左下角的坐标,(x2,y2)是该矩形右上角的坐标。 找出平面中所有矩形叠加覆盖后的总面积。 由于答案可能太大,请返回它对 10 ^ 9 + 7 取模的结果。 示例 1: 输入:[[0,0,2,2],[1,0,2,3],[1,0,3,1]] 输出:6 解释:如图所示。 示例 2: 输入:[[0,0,1000000000,1000000000]] 输出:49 解释:答案是 10^18 对 (10^9 + 7) 取模的结果, 即 (10^9)^2 → (-7)^2 = 49 。 提示: 1 <= rectangles.length <= 200 rectanges[i].length = 4 0 <= rectangles[i][j] <= 10^9 矩形叠加覆盖后的总面积不会超越 2^63 - 1 ,这意味着可以用一个 64 位有符号整数来保存面积结果。
解题算法:
class Solution { public: static bool cmp(vector<int> a,vector<int> b){ return a[1] < b[1]; } int getDeep(vector<vector<int>>& rectangles,int x1,int x2){ vector<pair<int,int>> deep; int length = 0; int start; int end; for(int i = 0;i < rectangles.size(); ++i){ if(x1 >= rectangles[i][0] && x2 <= rectangles[i][2]){ if(deep.empty()){ deep.push_back(make_pair(rectangles[i][1],rectangles[i][3])); }else{ end = deep[deep.size()-1].second; if(rectangles[i][1] <= end){ start = deep[deep.size()-1].first; end = max(end,rectangles[i][3]); deep.pop_back(); deep.push_back(make_pair(start,end)); }else{ deep.push_back(make_pair(rectangles[i][1],rectangles[i][3])); } } } } for(int i = 0;i < deep.size(); ++i){ length += deep[i].second - deep[i].first; } return length; } int rectangleArea(vector<vector<int>>& rectangles) { long long mod = 1000000000 + 7; long long area = 0; vector<long long> X; for(int i = 0;i < rectangles.size(); ++i){ X.push_back(rectangles[i][0]); X.push_back(rectangles[i][2]); } sort(X.begin(),X.end()); sort(rectangles.begin(),rectangles.end(),cmp); vector<long long>::iterator end_unique = unique(X.begin(), X.end()); X.erase(end_unique, X.end()); for(int i = 1;i < X.size(); ++i){ long long height = getDeep(rectangles,X[i-1],X[i]); long long width = X[i]-X[i-1]; area += (width*height)%mod; area = area%mod; } return area; } };