LeetCode-in-Java

2482. Difference Between Ones and Zeros in Row and Column

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:

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:

Example 2:

Input: grid = [[1,1,1],[1,1,1]]

Output: [[5,5,5],[5,5,5]]

Explanation:

Constraints:

Solution

public class Solution {
    public int[][] onesMinusZeros(int[][] grid) {
        int[] rowOne = new int[grid.length];
        int[] colOne = new int[grid[0].length];
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            int c = 0;
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    c++;
                }
            }
            rowOne[i] = c;
        }
        for (int i = 0; i < n; i++) {
            int c = 0;
            for (int[] ints : grid) {
                if (ints[i] == 1) {
                    c++;
                }
            }
            colOne[i] = c;
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                grid[i][j] = rowOne[i] + colOne[j] - (m - rowOne[i]) - (n - colOne[j]);
            }
        }
        return grid;
    }
}