@思路
问题链接:https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix/submissions/
思路
1,行和列分别累加数字
2,行和列分别计算奇数数量
3,使用公式算出总奇数数量
注意,此算法操作中一直以一维数组操作和数字操作,不要联想到二维而被思维误导。
效率
执行用时 :56 ms, 在所有 python3 提交中击败了71.23% 的用户
内存消耗 :13.8 MB, 在所有 python3 提交中击败了100.00%的用户
代码
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
rows = [0] * n
cols = [0] * m
for x,y in indices:
rows[x] += 1 #一维数组元素
cols[y] += 1
raws_odd = sum(i%2 == 1 for i in rows)
cols_odd = sum(i%2 == 1 for i in cols)
return raws_odd * m + cols_odd * n - 2 * cols_odd * raws_odd