题目链接:
完美矩形
有关题目
给你一个数组 rectangles ,其中 rectangles[i] = [xi, yi, ai, bi] 表示一个坐标轴平行的矩形。这个矩形的左下顶点是 (xi, yi) ,右上顶点是 (ai, bi) 。
如果所有矩形一起精确覆盖了某个矩形区域,则返回 true ;否则,返回 false 。
示例 1:
输入:rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
输出:true
解释:5 个矩形一起可以精确地覆盖一个矩形区域。
示例 2:
输入:rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]
输出:false
解释:两个矩形之间有间隔,无法覆盖成一个矩形。
示例 3:
输入:rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[3,2,4,4]]
输出:false
解释:图形顶端留有空缺,无法覆盖成一个矩形。
示例 4:
输入:rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]
输出:false
解释:因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
提示:
1 <= rectangles.length <= 2 * 10^4
rectangles[i].length == 4
-10^5 <= xi, yi, ai, bi <= 10^5
题解
法一:哈希表 + 计数 参考官方题解
代码一:
class Solution {
public:
typedef pair<int, int> Point;
bool isRectangleCover(vector<vector<int>>& rectangles) {
int minX = INT_MAX, minY = INT_MAX, maxX = INT_MIN, maxY = INT_MIN;
int areaSum = 0;
map<Point, int> mp;
for (auto &rec : rectangles)
{
int x = rec[0], y = rec[1], a = rec[2], b = rec[3];
areaSum += (a - x) * (b - y);
minX = min(x, minX);
minY = min(y, minY);
maxX = max(a, maxX);
maxY = max(b, maxY);
Point point1({x, y});
Point point2({x, b});
Point point3({a, y});
Point point4({a, b});
++mp[point1];
++mp[point2];
++mp[point3];
++mp[point4];
}
Point pminmin({minX, minY});
Point pminmax({minX, maxY});
Point pmaxmin({maxX, minY});
Point pmaxmax({maxX, maxY});
if (areaSum != (long long)(maxX - minX) * (maxY - minY)
|| !mp.count(pminmin) || !mp.count(pminmax)
|| !mp.count(pmaxmin) || !mp.count(pmaxmax))
return false;
mp.erase(pminmin);
mp.erase(pminmax);
mp.erase(pmaxmin);
mp.erase(pmaxmax);
for (auto &p : mp)
{
if (p.second % 2 != 0)
return false;
}
return true;
}
};
代码二: 参考官方题解评论区下Slender_
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
int areaSum = 0;
map<pair<int,int>, int> mp;
vector<pair<int, int>> vPoint;
int minX = INT_MAX, minY = INT_MAX, maxA = INT_MIN, maxB = INT_MIN;
for (auto &rec : rectangles)
{
int x = rec[0], y = rec[1], a = rec[2], b = rec[3];
areaSum += (a - x) * (b - y);
++mp[make_pair(x, y)];
++mp[make_pair(x, b)];
++mp[make_pair(a, y)];
++mp[make_pair(a, b)];
}
for (auto &p : mp)
{
if (p.second == 1)
{
vPoint.push_back(p.first);
minX = min(minX, p.first.first);
minY = min(minY, p.first.second);
maxA = max(maxA, p.first.first);
maxB = max(maxB, p.first.second);
}
else if (p.second % 2 != 0)
return false;
}
return (vPoint.size() == 4) && ((maxA - minX) * (maxB - minY) == areaSum);
}
};
|