Java: straightforward approach


  • 0
    E
    public class Solution {
        public void setZeroes(int[][] matrix) {
            // Initialize variables to keep track of rows and columns
            // that we are going to nullify
            Set<Integer> rowsToNullify = new HashSet<>();
            Set<Integer> colsToNullify = new HashSet<>();
            // Scan through the matrix and find rows and columns
            // that are going to be nullified
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[0].length; j++) {
                    if (matrix[i][j] == 0) {
                        rowsToNullify.add(i);
                        colsToNullify.add(j);
                    }
                }
            }
            // Nullify rows
            for (int n : rowsToNullify) {
                nullifyRow(matrix, n);
            }
            // Nullify columns
            for (int n : colsToNullify) {
                nullifyCol(matrix, n);
            }
        }
        
        private void nullifyRow(int[][] matrix, int row) {
            for (int i = 0; i < matrix[0].length; i++) {
                matrix[row][i] = 0;
            }
        }
        
        private void nullifyCol(int[][] matrix, int col) {
            for (int i = 0; i < matrix.length; i++) {
                matrix[i][col] = 0;
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.