Problem
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 beonesRowi
.Let the number of ones in the
jth
column beonesColj
.Let the number of zeros in the
ith
row bezerosRowi
.Let the number of zeros in the
jth
column bezerosColj
.diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
Return the difference matrix diff
.
Example 1:
Input: grid = [[0,1,1],[1,0,1],[0,0,1]]
Output: [[0,0,4],[0,0,4],[-2,-2,2]]
Explanation:
- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0
- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0
- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4
- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0
- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0
- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4
- diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2
- diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2
- diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2
Example 2:
Input: grid = [[1,1,1],[1,1,1]]
Output: [[5,5,5],[5,5,5]]
Explanation:
- diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5
- diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5
- diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5
- diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5
- diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5
- diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
grid[i][j]
is either0
or1
.
Solution (Java)
class Solution {
public int[][] onesMinusZeros(int[][] arr) {
int m = arr.length;
int n = arr[0].length;
int ans [][] = new int[m][n];
int row = 0;
for(int i = 0 ; i < m ; i++) {
int one = 0;
for(int j = 0 ; j < n ; j++) {
if(arr[i][j] == 1)one++;
}
ans[i][n-1] = one;
if(i == m-1) row = one;
}
for(int i = 0 ; i < n ; i++) {
int one = 0;
for(int j = 0 ; j < m ; j++) {
if(arr[j][i] == 1)one++;
}
ans[m-1][i] = one;
}
for(int i = 0 ; i < m-1 ; i++) {
for(int j = 0 ; j < n ; j++) {
int put = ans[m-1][j] + ans[i][n-1] - (m-ans[m-1][j]+n-ans[i][n-1]);
ans[i][j] = put;
}
}
for(int i = m-1 ; i < m ; i++) {
for(int j = 0 ; j < n ; j++) {
int put = ans[m-1][j] + row - (m-ans[m-1][j]+n-row);
ans[i][j] = put;
}
}
return ans;
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(1).