2482-行和列中一和零的差值

Raphael Liu Lv10

给你一个下标从 0 开始的 m x n 二进制矩阵 grid

我们按照如下过程,定义一个下标从 0 开始的 m x n 差值矩阵 diff

  • 令第 i 行一的数目为 onesRowi
  • 令第 j 列一的数目为 onesColj
  • 令第 i 行零的数目为 zerosRowi
  • 令第 j 列零的数目为 zerosColj
  • diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj

请你返回差值矩阵 _ _diff

示例 1:

**输入:** grid = [[0,1,1],[1,0,1],[0,0,1]]
**输出:** [[0,0,4],[0,0,4],[-2,-2,2]]
**解释:**
- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0 
- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0 
- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4 
- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0 
- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0 
- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4 
- diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2
- diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2
- diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2

示例 2:

**输入:** grid = [[1,1,1],[1,1,1]]
**输出:** [[5,5,5],[5,5,5]]
**解释:**
- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5
- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5
- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5
- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5
- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5
- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5

提示:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 105
  • 1 <= m * n <= 105
  • grid[i][j] 要么是 0 ,要么是 1

视频讲解 已出炉,欢迎点赞三连,在评论区分享你对这场双周赛的看法~


按要求模拟。

优化 1:由于行和列都可以看成是 1 的个数减去 0 的个数,所以统计的时候,可以把 0 当成 -1。

优化 2:答案可以直接填到 grid 中。

[sol1-Python3]
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
r = [0] * len(grid)
c = [0] * len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
r[i] += x * 2 - 1
c[j] += x * 2 - 1 # 1 -> 1, 0 -> -1
for i, x in enumerate(r):
for j, y in enumerate(c):
grid[i][j] = x + y
return grid
[sol1-Go]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func onesMinusZeros(grid [][]int) [][]int {
r := make([]int, len(grid))
c := make([]int, len(grid[0]))
for i, row := range grid {
for j, x := range row {
r[i] += x*2 - 1
c[j] += x*2 - 1 // 1 -> 1, 0 -> -1
}
}
for i, x := range r {
for j, y := range c {
grid[i][j] = x + y
}
}
return grid
}

复杂度分析

  • 时间复杂度:O(mn),其中 m 和 n 分别为 grid 的行数和列数。
  • 空间复杂度:O(m+n)。
 Comments
On this page
2482-行和列中一和零的差值