三刷
53.79 %
class Solution {
public boolean isValidSudoku(char[][] board) {
Set<Integer> row = new HashSet<>();
Set<Integer> col = new HashSet<>();
Set<Integer> cube = new HashSet<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (Character.isDigit(board[i][j]) && !row.add((int) (board[i][j] - 'a'))) {
return false;
}
if (Character.isDigit(board[j][i]) && !col.add((int) (board[j][i] - 'a'))) {
return false;
}
int y = (i / 3) * 3 + (j / 3);
int x = (i % 3) * 3 + (j % 3);
if (Character.isDigit(board[y][x]) && !cube.add((int) (board[y][x] - 'a'))) {
return false;
}
}
row.clear();
col.clear();
cube.clear();
}
return true;
}
}
二刷
Next solution is better
42.04 %
class Solution {
public boolean isValidSudoku(char[][] board) {
List<Set<Integer>> rows = new ArrayList<>();
List<Set<Integer>> cols = new ArrayList<>();
List<Set<Integer>> subBoxes = new ArrayList<>();
for (int i = 0; i < 9; i++) {
rows.add(new HashSet<>());
cols.add(new HashSet<>());
subBoxes.add(new HashSet<>());
}
for (int y = 0; y < board.length; y++) {
for (int x = 0; x < board[0].length; x++) {
if (Character.isDigit(board[y][x])) {
int num = (int) (board[y][x] - '0');
if (!rows.get(y).add(num)) {
return false;
}
if (!cols.get(x).add(num)) {
return false;
}
int boxId = y / 3 * 3 + (x / 3);
if (!subBoxes.get(boxId).add(num)) {
return false;
}
}
}
}
return true;
}
}
一刷
49.94 %
class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0] == null || board[0].length != 9) return false;
Set<Character> row = new HashSet<>();
Set<Character> col = new HashSet<>();
Set<Character> cube = new HashSet<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// for ith row
if (board[i][j] != '.' && !row.add(board[i][j])) return false;
if (board[j][i] != '.' && !col.add(board[j][i])) return false;
int x = (i / 3) * 3 + j / 3;
int y = (i % 3) * 3 + j % 3;
if (board[x][y] != '.' && !cube.add(board[x][y])) return false;
}
row.clear();
col.clear();
cube.clear();
}
return true;
}
}
41.01 %
class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0] == null || board[0].length != 9) return false;
Set<Integer> row = new HashSet<>();
Set<Integer> col = new HashSet<>();
Set<Integer> cube = new HashSet<>();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// for ith row
if (board[i][j] != '.' && !row.add(Character.getNumericValue(board[i][j]))) return false;
if (board[j][i] != '.' && !col.add(Character.getNumericValue(board[j][i]))) return false;
int x = (i / 3) * 3 + j / 3;
int y = (i % 3) * 3 + j % 3;
if (board[x][y] != '.' && !cube.add(Character.getNumericValue(board[x][y]))) return false;
}
row.clear();
col.clear();
cube.clear();
}
return true;
}
}
No comments:
Post a Comment