[LeetCode] Difference Between Ones and Zeros in Row and Column

2482. Difference Between Ones and Zeros in Row and Column

You are given a 0-indexed m x n binary matrix grid.

A 0-indexed m x n difference matrix diff is created with the following procedure:

  • Let the number of ones in the ith row be onesRowi.
  • Let the number of ones in the jth column be onesColj.
  • Let the number of zeros in the ith row be zerosRowi.
  • Let the number of zeros in the jth column be zerosColj.
  • diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj

Return the difference matrix diff.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

class Solution {
public:
vector<vector<int>> onesMinusZeros(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
vector<int> ro(n), rz(n), co(m), cz(m);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == 0) {
rz[i] += 1;
cz[j] += 1;
} else {
ro[i] += 1;
co[j] += 1;
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
A[i][j] = ro[i] + co[j] - rz[i] - cz[j];
}
}
return A;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/26/PS/LeetCode/difference-between-ones-and-zeros-in-row-and-column/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.