⬆︎
×

[LC] 2482 Difference Between Ones and Zeros in Row and Column

Java

/**
 * <a href="https://leetcode.cn/problems/difference-between-ones-and-zeros-in-row-and-column/">Difference Between Ones and Zeros in Row and Column</a>
 * 数组;矩阵;模拟
 */
class Solution {
    /**
     * 预处理模拟
     */
    public int[][] onesMinusZeros(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;

        int[] rows = new int[m]; // 记录每一行1和0数目的差值
        int[] cols = new int[n]; // 记录每一列1和0数目的差值

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    rows[i]++;
                    cols[j]++;
                } else {
                    rows[i]--;
                    cols[j]--;
                }
            }
        }

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                grid[i][j] = rows[i] + cols[j];
            }
        }

        return grid;
    }
}

发表评论