Leetcode 1252:奇数值单元格的数目(超详细的解法!!!)

给你一个 nm 列的矩阵,最开始的时候,每个单元格中的值都是 0

另有一个索引数组 indicesindices[i] = [ri, ci] 中的 rici 分别表示指定的行和列(从 0 开始编号)。

你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1

请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。

示例 1:

输入:n = 2, m = 3, indices = [[0,1],[1,1]]
输出:6
解释:最开始的矩阵是 [[0,0,0],[0,0,0]]。
第一次增量操作后得到 [[1,2,1],[0,1,0]]。
最后的矩阵是 [[1,3,1],[1,3,1]],里面有 6 个奇数。

示例 2:

输入:n = 2, m = 2, indices = [[1,1],[0,0]]
输出:0
解释:最后的矩阵是 [[2,2],[2,2]],里面没有奇数。

提示:

  • 1 <= n <= 50
  • 1 <= m <= 50
  • 1 <= indices.length <= 100
  • 0 <= indices[i][0] < n
  • 0 <= indices[i][1] < m

解题思路

首先这个问题使用暴力法就能过,暴力法的思路就是模拟题目的过程。

class Solution:
    def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
        g = [[0] * m for _ in range(n)]
        for i, j in indices:
            for k in range(m):
                g[i][k] += 1
            for k in range(n):
                g[k][j] += 1
        res = 0
        for i in range(n):
            for j in range(m):
                if g[i][j] & 1:
                    res += 1
        return res

但是实际上我们并不需要模拟一遍,我们只要统计每一行和每一列中有多少变化了奇数次。需要注意的是,当一个位置的横坐标变化奇数次并且纵坐标也变化奇数次,那么此时相当于变化了偶数次,所以不用记录。

class Solution:
    def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
        row, col = [False] * n, [False] * m
        for r, c in indices:
            row[r] ^= True
            col[c] ^= True
        return m * sum(row) + n * sum(col) - 2 * sum(row) * sum(col)

根据上面的性质,我们还可以使用xor运算(也就是不带进位的加法)。

return sum(ro ^ cl for ro in row for cl in col) # last

这里有一步小优化,通过变量记录1出现的次数。

class Solution:
    def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
        row, col, cntRow, cntCol = [False] * n, [False] * m, 0, 0
        for r, c in indices:
            row[r] ^= True
            col[c] ^= True
            cntRow += 1 if row[r] else -1 
            cntCol += 1 if col[c] else -1 
        return m * cntRow + n * cntCol - 2 * cntRow * cntCol

当然这里你可以使用汉明重量来计算1出现的次数。

reference:

https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/425100/JavaPython-3-2-methods%3A-time-O(m-*-n-%2B-L)-and-O(L)-codes-w-comment-and-analysis.

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值