comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
中等 |
1348 |
第 403 场周赛 Q2 |
|
给你一个二维 二进制 数组 grid
。请你找出一个边在水平方向和竖直方向上、面积 最小 的矩形,并且满足 grid
中所有的 1 都在矩形的内部。
返回这个矩形可能的 最小 面积。
示例 1:
示例 2:
提示:
1 <= grid.length, grid[i].length <= 1000
grid[i][j]
是 0 或 1。- 输入保证
grid
中至少有一个 1 。
我们可以遍历 grid
,找到所有 1
的最小边界,记为
时间复杂度 grid
的行数和列数。空间复杂度
class Solution:
def minimumArea(self, grid: List[List[int]]) -> int:
x1 = y1 = inf
x2 = y2 = -inf
for i, row in enumerate(grid):
for j, x in enumerate(row):
if x == 1:
x1 = min(x1, i)
y1 = min(y1, j)
x2 = max(x2, i)
y2 = max(y2, j)
return (x2 - x1 + 1) * (y2 - y1 + 1)
class Solution {
public int minimumArea(int[][] grid) {
int m = grid.length, n = grid[0].length;
int x1 = m, y1 = n;
int x2 = 0, y2 = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
x1 = Math.min(x1, i);
y1 = Math.min(y1, j);
x2 = Math.max(x2, i);
y2 = Math.max(y2, j);
}
}
}
return (x2 - x1 + 1) * (y2 - y1 + 1);
}
}
class Solution {
public:
int minimumArea(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
int x1 = m, y1 = n;
int x2 = 0, y2 = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 1) {
x1 = min(x1, i);
y1 = min(y1, j);
x2 = max(x2, i);
y2 = max(y2, j);
}
}
}
return (x2 - x1 + 1) * (y2 - y1 + 1);
}
};
func minimumArea(grid [][]int) int {
x1, y1 := len(grid), len(grid[0])
x2, y2 := 0, 0
for i, row := range grid {
for j, x := range row {
if x == 1 {
x1, y1 = min(x1, i), min(y1, j)
x2, y2 = max(x2, i), max(y2, j)
}
}
}
return (x2 - x1 + 1) * (y2 - y1 + 1)
}
function minimumArea(grid: number[][]): number {
const [m, n] = [grid.length, grid[0].length];
let [x1, y1] = [m, n];
let [x2, y2] = [0, 0];
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
if (grid[i][j] === 1) {
x1 = Math.min(x1, i);
y1 = Math.min(y1, j);
x2 = Math.max(x2, i);
y2 = Math.max(y2, j);
}
}
}
return (x2 - x1 + 1) * (y2 - y1 + 1);
}