LeetCode 풀기 - 73. Set Matrix Zeros

백지우·2026년 9월 17일

LeetCode

목록 보기
55/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

73. Set Matrix Zeros

풀이

  • 방법: 한번씩 돌면서 0인 row, col 저장 이후 다시 row -> col 순으로 조정
class Solution {
    public void setZeroes(int[][] matrix) {
        List<Integer> row = new ArrayList();
        List<Integer> col = new ArrayList();

        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == 0){
                    row.add(i);
                    col.add(j);
                }
            }
        }
        for(int i = 0; i < row.size(); i++){
            Arrays.fill(matrix[row.get(i)], 0);
        }

        for(int i = 0; i < col.size(); i++){
            for(int[] r: matrix){
                r[col.get(i)] = 0;
            }
        }
    }
}
  • 코드 작성하다가 느낀점
    - 너무 정직한 풀이인데

두번째 풀이

  • 방법: 공간을 줄이기 위하여 matrix의 첫 행, 첫 열을 저장공간으로 활용. 공간복잡도 O(1)
class Solution {
    public void setZeroes(int[][] matrix) {
        boolean row_0 = false;
        boolean col_0 = false;

        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(matrix[i][j] == 0){
                    if(i == 0) row_0 = true;
                    if(j == 0) col_0 = true;
                    
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                    
                }
            }
        }
        
        for(int i = 1; i < matrix.length; i++){
            for(int j = 1; j < matrix[0].length; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        if(row_0) Arrays.fill(matrix[0], 0);
        if(col_0){
            for (int i = 0; i < matrix.length; i++){
                matrix[i][0] = 0;
            }
        }
    }
}

0개의 댓글