My O(n) solution. n is 81


  • 1
    A
    public class Solution {
    public boolean isValidSudoku(char[][] board) {
        if(board.length != 9)
        {
            return false;
        }
        //check whether size is correct
        ArrayList<HashSet<Integer>> cols = new ArrayList<HashSet<Integer>>();
        ArrayList<HashSet<Integer>> boxes = new ArrayList<HashSet<Integer>>();
        for (int i = 0; i < 9; i++)
        {
            HashSet<Integer> a = new HashSet<Integer>();
            cols.add(a);
            HashSet<Integer> b = new HashSet<Integer>();
            boxes.add(b);
        }
        for(int i = 0; i < board.length; i++)
        {
            HashSet<Integer> line = new HashSet<Integer>();
            for(int j = 0; j < board[i].length; j ++)
            {
                if (board[i].length != 9)
                {
                    return false;
                }
                char cval = board[i][j];
                if(cval == '.')
                    continue;
                int val = Integer.parseInt(cval+"");
                if(val < 1 || val > 9)
                {
                    return false;
                }
                int bind = (i/3)*3+(j/3);
                if(line.contains(val)|| cols.get(j).contains(val) || boxes.get(bind).contains(val))
                {
                    return false;
                }
                line.add(val);
                cols.get(j).add(val);
                boxes.get(bind).add(val);
            }
        }
        return true;
    }
    

    }

    Use 19 hashsets to record previously visited elements


Log in to reply
 

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