Easy Understanding Java Sol - beat over than 90%, no extra space


  • 2
    R
    public class Solution {
        public boolean isValidSudoku(char[][] board) {
            for(int i = 0; i < board.length; i++){
                for(int j = 0; j < board[0].length; j++){
                    char c = board[i][j];
                    if(c == '.')
                        continue;
                    if(!isValid(board,i,j,c))
                        return false;
                }
            }
            
            return true;
            
        }
        
        public boolean isValid(char[][] board, int row, int col, char c){
            for(int i = 0; i < 9; i++){
                if(col != i && board[row][i] == c)
                    return false;
            }
            
            for(int j = 0; j < 9; j++){
                if(row != j && board[j][col] == c)
                    return false;
            }
            
            for(int i = row / 3 * 3; i < row / 3 * 3 + 3; i++){
                for(int j = col / 3 * 3; j < col / 3 * 3 + 3; j++){
                    if(board[i][j] == c){
                        if(row == i && col == j)
                            continue;
                        return false;
                    }
                }
            }
            
            return true;
        }
        
        
    }

  • 1
    H

    can you tell me what makes this run so much faster than the top rated solutions which use a hashset?

    you check each character in the array for its row, column and box to ensure the same value isnt there

    whereas they check each row, column and box for duplicates

    i dont really understand what makes yours faster...


  • 0
    F

    Having the same doubt.
    Actually, it should be one of the slowest solutions although mine is totally the same with it.


Log in to reply
 

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