力扣 36 有效的数独

题目

题目详情

解法

  • 解法一

3次for循环, O(n^2)
超时

class Solution {
    public boolean isValidSudoku(char[][] board) {

        Set<Character> set = new HashSet<>(9);
        for (int i = 0; i < 9; i ++){
            for (int j = 0; j < 9; j++){
                if (set.contains(board[i][j]) && board[i][j] != '.'){
                    return false;
                }
                set.add(board[i][j]);
            }
            set.clear();
        }
        
        for (int i = 0; i < 9; i ++){
            for (int j = 0; j < 9; j++){
                if (set.contains(board[j][i]) && board[j][i] != '.'){
                    return false;
                }
                set.add(board[j][i]);
            }
            set.clear();
        }
        
    
        for (int j = 0, i = 0; j < 9; j ++){
            if (j % 3 == 0 && j != 0){
                i ++;
                j = 0;
                if (i % 3 == 0 && i != 0){
                    set.clear();
                }
                if (i == 9){
                    i = 0;
                    j += 3;
                } 
            }
            if (set.contains(board[i][j]) && board[i][j] != '.'){
                  return false;
            }
            set.add(board[i][j]);
        }
        return true;
    }
}
  • 解法二

一次遍历 , 可以说是用空间换时间

class Solution {
    public boolean isValidSudoku(char[][] board) {

        Set<Character> [] rows = new HashSet[9];
        Set<Character> [] columns = new HashSet[9];
        Set<Character> [] boxes = new HashSet[9];
        
        for (int i = 0; i < 9; i ++){
            rows[i] = new HashSet<>(9);
            columns[i] = new HashSet<>(9);
            boxes[i] = new HashSet<>(9);
        }
        
        for (int i = 0; i < 9; i ++){
            for (int j = 0; j < 9; j ++){
                char num = board[i][j];
                int boxIndex = (i / 3 ) * 3 + j / 3;
                if ((rows[i].contains(num) || columns[j].contains(num) || boxes[boxIndex].contains(num)) && num != '.'){
                    return false;
                }
                rows[i].add(num);
                columns[j].add(num);
                boxes[boxIndex].add(num);
            }
        }
        return true;
    }
}

你可能感兴趣的:(刷刷刷)