解法一:击败 54%
import java.util.HashSet;
public class Solution {
public static boolean isValidSudoku(char[][] board) {
for (int i = 0; i < board.length; i++) {
HashSet<Character> rows = new HashSet<Character>();//行
HashSet<Character> cols = new HashSet<Character>();//列
HashSet<Character> cube = new HashSet<Character>();//9宫格
for (int j = 0; j < board[0].length; j++) {
//行 有没有重复
if (board[i][j] != '.' && !rows.add(board[i][j])) {
System.out.println(1111111);
return false;
}
//列 有没有重复
if (board[j][i] != '.' && !cols.add(board[j][i])) {
System.out.println(j + "------>" + i);
return false;
}
//cube 有没有重复
/**
* rowCube 0 0 0 3 3 3 6 6 6
* colCube 0 3 6 0 3 6 0 3 6
* 下面几行写的很巧妙 望大家细细琢磨 画画图
*/
int rowCube = 3 * (i / 3);
int colCube = 3 * (i % 3);
if (board[rowCube + j / 3][colCube + j % 3] != '.'
&& !cube.add(board[rowCube + j / 3][(colCube + j % 3)])) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
char[][] strs = {
{'5','3','.','.','7','.','.','.','.'},
{'6','.','.','1','9','5','.','.','.'},
{'.','9','8','.','.','.','.','6','.'},
{'8','.','.','.','6','.','.','.','3'},
{'4','.','.','8','.','3','.','.','1'},
{'7','.','.','.','2','.','.','.','6'},
{'.','6','.','.','.','.','2','8','.'},
{'.','.','.','4','1','9','.','.','5'},
{'.','.','.','.','8','.','.','7','9'} };
boolean flag = isValidSudoku(strs);
System.out.println(flag);
}
}
解法2 :击败 90%+
class Solution {
public static boolean isValidSudoku(char[][] board) {
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if(board[i][j] == '.')continue;
for(int k = 8; k > j; k--)
if(board[i][j] == board[i][k])
return false;
for(int k = 8; k > i; k--)
if(board[i][j] == board[k][j])
return false;
for(int k = i + 1; k % 3 != 0; k ++){
for(int h = j / 3 * 3;h < j / 3 * 3 + 3; h ++ )
if(board[i][j] == board[k][h])
return false;
}
}
}
return true;
}
}
在小样本情况下,算法的时间问题,还要就具体问题而论。