[코테 풀이] Difference Between Ones and Zeros in Row and Column

시내·2024년 6월 26일

Q_2482) Difference Between Ones and Zeros in Row and Column

출처 : https://leetcode.com/problems/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.

1st Try: 시간 초과 이슈 O(n^3)

class Solution {
    public int[][] onesMinusZeros(int[][] grid) {
        int[][] diff = new int[grid.length][grid[0].length];
        for (int a = 0; a < diff.length; a++) {
            for (int b = 0; b < diff[0].length; b++) {
                diff[a][b] = rowCount(1, a, grid) + colCount(1, b, grid) 
                - rowCount(0, a, grid) - colCount(0, b, grid);
            }
        }
        return diff;
    }
    
    public int colCount(int target, int colNum, int[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            if (grid[i][colNum] == target) count++;
        }
        return count;
    }

    public int rowCount(int target, int rowNum, int[][] grid) {
        int count = 0;
        for (int i = 0; i < grid[0].length; i++) {
            if (grid[rowNum][i] == target) count++;
        }
        return count;
    }
}

2nd Try: O(n^2)

{
        int[][] diff = new int[grid.length][grid[0].length];
        int[] onesRow = new int[grid.length];
        int[] zerosRow = new int[grid.length];
        int[] onesCol = new int[grid[0].length];
        int[] zerosCol = new int[grid[0].length];
        
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    onesRow[i]++;
                    onesCol[j]++;
                } else {
                    zerosRow[i]++;
                    zerosCol[j]++;
                }
            }
        }

        for (int a = 0; a < diff.length; a++) {
            for (int b = 0; b < diff[0].length; b++) {
                diff[a][b] = onesRow[a] + onesCol[b] 
                - zerosRow[a] - zerosCol[b];
            }
        }
        return diff;
    }

🙈 풀이 참조해서 푼 문제
애초에 0와 1을 가진 Row와 Column 각각의 int[] 배열을 만들어서 저장해둔다.
그렇규나

profile
contact 📨 ksw08215@gmail.com

0개의 댓글