列表

详情


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

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

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

请你返回差值矩阵 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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: vector<vector<int>> onesMinusZeros(vector<vector<int>>& grid) { } };

golang 解法, 执行用时: 184 ms, 内存消耗: 22.3 MB, 提交时间: 2022-12-01 09:51:45

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
}

python3 解法, 执行用时: 264 ms, 内存消耗: 34.2 MB, 提交时间: 2022-12-01 09:51:25

'''
按要求模拟。

优化 1:由于行和列都可以看成是 1 的个数减去 0 的个数,所以统计的时候,可以把 0 当成 −1。
优化 2:答案可以直接填到 grid 中。
'''
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

上一题