有效数独

链接:
https://leetcode-cn.com/problems/valid-sudoku/

1.使用数组解决;

点击查看代码
//使用数组解决;
class Solution {
    public boolean isValidSudoku(char[][] board) {
//分别对应,横,纵,正方体中的数字组合;
    boolean[][] row = new boolean[9][10], col = new boolean[9][10], area = new boolean[9][10]; 
    for(int i=0;i<9;i++){
        for(int a=0;a<9;a++){
            int tem=board[i][a];
              //判断这个是否是空,是空下一个
             if(tem=='.'){
                continue;
            }
              //因为是char类型转int,存储的是asll码,减去'0'asll码就正常了;
            int iem=tem-'0';
              //计算是哪个正方形中的数字
            int k= i/3*3+a/3;
              //初始化数组存储的都是false,若有true证明重复;
            if(row[i][iem]||col[a][iem]||area[k][iem]){
return false;
            }
              //赋值ture;
            row[i][iem]=true;
            col[a][iem]=true;
            area[k][iem]=true;
        }
    }
return true;
    }
}


空间复杂度:O(1)
时间复杂度:O(1)
因为都是固定的9*9方格子;

2.还可以使用哈希表

点击查看代码
//与数组方法大同小异
class Solution {
    public boolean isValidSudoku(char[][] board) {
        Map<Integer, Set<Integer>> row  = new HashMap<>(), col = new HashMap<>(), area = new HashMap<>();
        for (int i = 0; i < 9; i++) {
            row.put(i, new HashSet<>());
            col.put(i, new HashSet<>());
            area.put(i, new HashSet<>());
        }
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c == '.') continue;
                int u = c - '0';
                int idx = i / 3 * 3 + j / 3;
                if (row.get(i).contains(u) || col.get(j).contains(u) || area.get(idx).contains(u)) return false;
                row.get(i).add(u);
                col.get(j).add(u);
                area.get(idx).add(u);
            }
        }
        return true;
    }
}


空间复杂度:O(1)
时间复杂度:O(1)

posted @ 2022-02-02 23:40  蜗牛卷  阅读(52)  评论(0)    收藏  举报