일상용/연습장

리트코드 11일차

alpakaka 2025. 2. 14. 19:15

73. Set Matrix Zeroes

class Solution {
    public void setZeroes(int[][] matrix) {
        HashSet<Integer> rows = new HashSet<>();
        HashSet<Integer> cols = new HashSet<>();

        for (int x= 0; x < matrix.length; x++){
            for (int y = 0; y < matrix[0].length; y++){
                if (matrix[x][y] == 0){
                    rows.add(x);
                    cols.add(y);
                }
            }
        }
        for (int x= 0; x < matrix.length; x++){
            for (int y = 0; y < matrix[0].length; y++){
                if (rows.contains(x) || cols.contains(y)){
                    matrix[x][y] = 0;
                }
            }
        }

    }
}

간단하게 이런식으로 만들었는데 2ms 나 나온다...

1ms 였으면 좋겠다. 어떻게 할 수 있을까?

class Solution {
    public void setZeroes(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        boolean firstRowHasZero = false;
        boolean firstColHasZero = false;

        for (int r = 0; r < rows; r++) {
            if (matrix[r][0] == 0) {
                firstColHasZero = true;
                break;
            }
        }

        for (int c = 0; c < cols; c++) {
            if (matrix[0][c] == 0) {
                firstRowHasZero = true;
                break;
            }
        }

        for (int x= 1; x < rows; x++){
            for (int y = 1; y < cols; y++){
                if (matrix[x][y] == 0){
                    matrix[x][0] = 0;
                    matrix[0][y] = 0;
                }
            }
        }

        for (int r = 1; r < rows; r++) {
            if (matrix[r][0] == 0) {
                for (int c = 1; c < cols; c++) {
                    matrix[r][c] = 0;
                }
            }
        }

        for (int c = 1; c < cols; c++) {
            if (matrix[0][c] == 0) {
                for (int r = 1; r < rows; r++) {
                    matrix[r][c] = 0;
                }
            }
        }

        if (firstRowHasZero) {
            for (int c = 0; c < cols; c++) {
                matrix[0][c] = 0;
            }
        }

        if (firstColHasZero) {
            for (int r = 0; r < rows; r++) {
                matrix[r][0] = 0;
            }
        }  
    }
}

이런식으로 작성하면 1ms 가 나온다. 방법은 1행 1열을 메모장처럼 쓰라는 답지를 보았기 때문이다.

이런식으로 하면 된다는데 사실 큰 차이는 잘 모르겠다. 그리고 여러번 돌려보니까 어떨땐 4ms나오고... 어떨땐 0ms나오고.. 약간 서버 자체가 불안정한 것 같기도 하다. 오늘따라.. 처음으로 오래걸린다고 서버에서 튕기기도 했다...ㅎㅎ