Sharing my simple Java solution


  • 1
    S
    public class Solution {
    public void setZeroes(int[][] matrix) {
        
        HashSet<Integer> row = new HashSet<Integer>();
        HashSet<Integer> col = new HashSet<Integer>();
        
        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 < matrix.length; i++){
                for(int j = 0; j < matrix[0].length; j++){
                    if(row.contains(i) || col.contains(j)){
                         matrix[i][j] = 0;
                }
            }
        }
    }
    

    }

    I am sharing my solution because I thought this could be easier to understand. But I am not sure if using hashset means extra space? Can anyone tell me how to improve the code or how to solve this question by using "constant space"? Thanks in advance.


  • 0
    L

    yep, using hash set means extra space. you can use the cell of first row to indicate whether that column should be set 0 and use the cell of first column to indicate whether that row should be set 0. And use constant extra space to indicate whether first row and first column should be set 0.


Log in to reply
 

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