Leetcode 391. Perfect Rectangle
程序员文章站
2022-07-13 12:00:59
...
正确的答案应当满足:
1.最大的长方形面积等于所有长方形的面积之和
2.除了四个顶点出现的次数为1,其他点出现次数必须为2/4次
class Solution {
public:
bool isRectangleCover(vector<vector<int>>& rectangles) {
//记录四边形顶点出现次数
unordered_map<string, int> vertex_count;
//记录总面积
int area = 0;
for (auto rect : rectangles) {
area += (rect[3] - rect[1]) * (rect[2] - rect[0]);
vector<string> vertex = { to_string(rect[0]) + '_' + to_string(rect[1]),
to_string(rect[2]) + '_' + to_string(rect[3]),
to_string(rect[0]) + '_' + to_string(rect[3]),
to_string(rect[2]) + '_' + to_string(rect[1]) };
for (auto v : vertex)
vertex_count[v]++;
}
// 四个顶点(出现一次)
vector<vector<int>> four_vertex;
for (auto iterator = vertex_count.begin(); iterator != vertex_count.end(); ++iterator) {
if (iterator->second == 1) {
int index = iterator->first.find('_');
four_vertex.push_back({ stoi(iterator->first.substr(0, index)), stoi(iterator->first.substr(index + 1)) });
}
//其他顶点出现2次或4次
else if (iterator->second != 2 && iterator->second != 4) {
return false;
}
}
if (four_vertex.size() != 4) {
return false;
}
int height = max(abs(four_vertex[0][1] - four_vertex[1][1]), abs(four_vertex[0][1] - four_vertex[2][1]));
int weight = max(abs(four_vertex[0][0] - four_vertex[1][0]), abs(four_vertex[0][0] - four_vertex[2][0]));
//所有长方形面积之和 = 通过四个顶点计算的总面积
if (height * weight != area) {
return false;
}
return true;
}
};
上一篇: Keras: fit_generator中如何构建一个generator?
下一篇: 数据解析之正则
推荐阅读
-
LeetCode解析------391.完美矩形
-
Leetcode 391. Perfect Rectangle
-
leetcode 85. Maximal Rectangle(最大全1子矩阵)
-
⭐⭐⭐⭐⭐【BFS求最小次数】LeetCode 279. Perfect Squares
-
leetcode 84 Largest Rectangle in Histogram (单调栈)
-
【Leetcode】223. Rectangle Area(计算两矩形覆盖总面积)
-
leetcode84. Largest Rectangle in Histogram 分治+线段树
-
leetcode 84 柱状图中最大矩形 / Largest Rectangle in Histogram