1. 题目
给你一个 n 行 m 列的矩阵,最开始的时候,每个单元格中的值都是 0。
另有一个索引数组 indices,indices[i] = [ri, ci] 中的 ri 和 ci 分别表示指定的行和列(从 0 开始编号)。
你需要将每对 [ri, ci] 指定的行和列上的所有单元格的值加 1。
请你在执行完所有 indices 指定的增量操作后,返回矩阵中 「奇数值单元格」 的数目。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
- 按照题目去模拟的效率是不高的
- 我们用两个数组去记录各行,各列出现的次数,出现偶数次,相当于没有变化
- 变化的行数有
r
,列数有c
,则奇数的个数应该为 r∗m+c∗n−2∗r∗cr*m+c*n-2*r*cr∗m+c∗n−2∗r∗c
class Solution {
public:int oddCells(int n, int m, vector<vector<int>>& indices) {int row[n] = {0}, column[m] = {0};for(auto &xy : indices){row[xy[0]]++;column[xy[1]]++;}int countR = 0, countC = 0;for(auto & i : row)if(i%2)countR++;for(auto & i : column)if(i%2)countC++;return countR*m + countC*n - 2*countR*countC;}
};