4ms java solution, ask for help on improvement on 3*3 block code


  • 0
    N

    public class Solution {

    public boolean isValidSudoku(char[][] board) {
        
        char[] testArray = new char[9];//always testing a 9 elements array
        
        //check rows;
        for(int i = 0; i<9; i++){
            for(int j = 0; j<9; j++){
                testArray[j]=board[i][j];
            }
            if(!isValid(testArray)){
                return false;
            }
        }
        
        //check columns;
        for(int j = 0; j <9; j++){
            for(int i = 0; i<9; i++){
                testArray[i]= board[i][j];
            }
            if(!isValid(testArray)){
                return false;
            }
        }
        
        
        //check 3*3 blocks;
        //****NEED IMPROVE****
        for(int i = 0; i<3; i++){
            for(int j = 0; j <3; j++){
                int counter = 0;
                for(int k = 0; k<3; k++){
                    for(int p =0; p<3; p++){
                        testArray[counter] = board[3*i+k][3*j+p];
                        counter++;
                    }
                }
                
                if(!isValid(testArray)){
                    return false;
                }
                
            }
            
        }
        
        return true;
    }
    
    
    /*
    test the char[9] array is valid or not
    @param char[] array
    @return boolean
    */
    public boolean isValid(char[] array){
        int[] numbers = new int[9];
        
        for(int i = 0; i<array.length; i++){
            if(array[i]!='.'){
                if(array[i]<'1'||array[i]>'9'){
                    return false;
                }
                else{
                    if(numbers[array[i]-'1']==1){
                        return false;
                    }
                    else{
                        numbers[array[i]-'1'] = 1;
                    }
                }
            }
        }
        return true;
    }
    

    }


  • 0
    A

    How is ur solution working in 4ms. I tried same and it gave me 31ms.


Log in to reply
 

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