关注 每天一道编程题 专栏,一起学习进步。
题目
Given n and m which are the dimensions of a matrix initialized by zeros and given an array indices where indices[i] = [ri, ci]. For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1.
Return the number of cells with odd values in the matrix after applying the increment to all indices.
Example 1:
Input: n = 2, m = 3, indices = [[0,1],[1,1]]
Output: 6
Explanation: Initial matrix = [[0,0,0],[0,0,0]].
After applying first increment it becomes [[1,2,1],[0,1,0]].
The final matrix will be [[1,3,1],[1,3,1]] which contains 6 odd numbers.
Example 2:
Input: n = 2, m = 2, indices = [[1,1],[0,0]]
Output: 0
Explanation: Final matrix = [[2,2],[2,2]]. There is no odd number in the final matrix.
Constraints:
1 <= n <= 50
1 <= m <= 50
1 <= indices.length <= 100
0 <= indices[i][0] < n
0 <= indices[i][1] < m
解析
- 给出n和m表示矩阵的行和列
- 给出一个二维数组,里面的每一个数对表示将该行/列加1
如[[0,1],[1,1]]意思是依次将第0行、第1列、第1行、第1列的数字加1. - 最后返回矩阵中奇数的个数。
算法思路:
最终返回的结果是“奇数的个数”,而非奇数之和等需要矩阵中具体数值的结果,也就是说,可以将题目转化为:状态为“奇数”、“偶数”,求出矩阵中的奇数状态数(状态可以转化为二进制或者布尔值)
此外,由于每次的操作都是加1,实际上就是将状态翻转一次。
运算符中符合这个翻转规则的是异或(0^1=1,1^1=0)
因此:
初始化矩阵全为0,对于给出的indices数组,每位与1进行异或操作,最后求出矩阵中1的个数(求出矩阵和)
解答
class Solution {
public int oddCells(int n, int m, int[][] indices) {
//初始化矩阵,将二维矩阵拆成两个一维矩阵
//java数组初始化默认消极值,boolean则为false,也就是全0阵
boolean[] oddRows = new boolean[n], oddCols = new boolean[m];
//上面行和列单独用的一维矩阵,因此这里也是单独将行和列的值拿出来
for (int[] idx : indices) {
//拿到每一位,与`1`进行异或操作
oddRows[idx[0]] ^= true;
oddCols[idx[1]] ^= true;
}
int cnt = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cnt += oddRows[i] ^ oddCols[j] ? 1 : 0;
}
}
return cnt;
}
}
最后这个矩阵求和我没搞懂。