Medium
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:
ith
row be onesRowi
.jth
column be onesColj
.ith
row be zerosRowi
.jth
column be zerosColj
.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:
onesRow0 + onesCol0 - zerosRow0 - zerosCol0
= 2 + 1 - 1 - 2 = 0onesRow0 + onesCol1 - zerosRow0 - zerosCol1
= 2 + 1 - 1 - 2 = 0onesRow0 + onesCol2 - zerosRow0 - zerosCol2
= 2 + 3 - 1 - 0 = 4onesRow1 + onesCol0 - zerosRow1 - zerosCol0
= 2 + 1 - 1 - 2 = 0onesRow1 + onesCol1 - zerosRow1 - zerosCol1
= 2 + 1 - 1 - 2 = 0onesRow1 + onesCol2 - zerosRow1 - zerosCol2
= 2 + 3 - 1 - 0 = 4onesRow2 + onesCol0 - zerosRow2 - zerosCol0
= 1 + 1 - 2 - 2 = -2onesRow2 + onesCol1 - zerosRow2 - zerosCol1
= 1 + 1 - 2 - 2 = -2onesRow2 + onesCol2 - zerosRow2 - zerosCol2
= 1 + 3 - 2 - 0 = 2Example 2:
Input: grid = [[1,1,1],[1,1,1]]
Output: [[5,5,5],[5,5,5]]
Explanation:
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
grid[i][j]
is either 0
or 1
.class Solution {
fun onesMinusZeros(grid: Array<IntArray>): Array<IntArray> {
val rowOne = IntArray(grid.size)
val colOne = IntArray(grid[0].size)
val m = grid.size
val n = grid[0].size
for (i in 0 until m) {
var c = 0
for (j in 0 until n) {
if (grid[i][j] == 1) {
c++
}
}
rowOne[i] = c
}
for (i in 0 until n) {
var c = 0
for (ints in grid) {
if (ints[i] == 1) {
c++
}
}
colOne[i] = c
}
for (i in 0 until m) {
for (j in 0 until n) {
grid[i][j] = rowOne[i] + colOne[j] - (m - rowOne[i]) - (n - colOne[j])
}
}
return grid
}
}