0036.有效的数独

方法一:遍历

因为数独大小固定为 O(9×9)O(9 \times 9),故时间复杂度 O(1)O(1),空间复杂度 O(1)O(1),均为常数级。

func isValidSudoku(board [][]byte) bool { // row, col, sub 分别表示第i行、第j列、第k个 3x3 宫内是否包含数字 1~9 中的某些数字 row, col, sub := [9][9]bool{}, [9][9]bool{}, [9][9]bool{} for i := 0; i < 9; i++ { for j := 0; j < 9; j++ { number := int(board[i][j] - byte('1')) if number < 0 || number >= 9 { continue } k := i/3*3 + j/3 if row[i][number] || col[j][number] || sub[k][number] { return false } row[i][number], col[j][number], sub[k][number] = true, true, true } } return true }