Java recode each 0 index, very easy understand


  • 0
    F

    Not thebest solution, but very easy understand!

    public class Solution {
        /**
         * @param matrix: A list of lists of integers
         * @return: Void
         */
        public void setZeroes(int[][] matrix) {
            // write your code here
            if (matrix == null) return;
            find_0(matrix);
        }
        private void find_0(int[][] matrix) {
            ArrayList<Integer> indexNote = new ArrayList<Integer>(); // indexNote using to record index which equal 0
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[0].length; j++) {
                    if (matrix[i][j] == 0) {
                        indexNote.add(i);
                        indexNote.add(j);
                    }
                }
            }
            set_0(matrix, indexNote);
        }
        private void set_0(int[][] matrix, ArrayList<Integer> indexNote) {
            for (int i = 1; i <= indexNote.size(); i+=2) {
                setRow_0(matrix, indexNote.get(i));
                setCol_0(matrix, indexNote.get(i - 1));
            }
        }
        private static void setRow_0(int[][] matrix, int col) {
            for (int i = 0; i < matrix.length; i++) {
                matrix[i][col] = 0;
            }
        }
        private static void setCol_0(int[][] matrix, int row) {
            for (int i = 0; i < matrix[row].length; i++) {
                matrix[row][i] = 0;
            }
        }
    }

Log in to reply
 

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