hashmap初始化
HashMap
<Integer, Integer> [] rows
= new HashMap[9];
HashMap
<Integer, Integer> [] columns
= new HashMap[9];
HashMap
<Integer, Integer> [] boxes
= new HashMap[9];
for (int i
= 0; i
< 9; i
++) {
rows
[i
] = new HashMap<>();
columns
[i
] = new HashMap<>();
boxes
[i
] = new HashMap<>();
}
Hashmap用于判断数组内是否重复,所以要会找隐藏的数组 比如对于数独问题,我们就可以每一行,每一列,每一个小数独都建造一个hsahmap数组。 当然,对于一次迭代来说: 每一个子数独应该用 (i/3)*3+(j/3); 这个子数独就是隐藏的数组
hashmap代码
class Solution {
public boolean isValidSudoku(char[][] board
) {
HashMap
<Integer, Integer> [] rows
= new HashMap[9];
HashMap
<Integer, Integer> [] columns
= new HashMap[9];
HashMap
<Integer, Integer> [] boxes
= new HashMap[9];
for (int i
= 0; i
< 9; i
++) {
rows
[i
] = new HashMap<Integer, Integer>();
columns
[i
] = new HashMap<Integer, Integer>();
boxes
[i
] = new HashMap<Integer, Integer>();
}
for (int i
= 0; i
< 9; i
++) {
for (int j
= 0; j
< 9; j
++) {
char num
= board
[i
][j
];
if (num
!= '.') {
int n
= (int)num
;
int box_index
= (i
/ 3 ) * 3 + j
/ 3;
rows
[i
].put(n
, rows
[i
].getOrDefault(n
, 0) + 1);
columns
[j
].put(n
, columns
[j
].getOrDefault(n
, 0) + 1);
boxes
[box_index
].put(n
, boxes
[box_index
].getOrDefault(n
, 0) + 1);
if (rows
[i
].get(n
) > 1 || columns
[j
].get(n
) > 1 || boxes
[box_index
].get(n
) > 1)
return false;
}
}
}
return true;
}
}
int i
= 0;
i
= i
| 1<<5;
System
.out
.println(i
);
i
= i
| 1<<4;
System
.out
.println(i
);
位运算代码
class Solution {
private final int N
= 9;
public boolean isValidSudoku(char[][] board
) {
int[] rows
= new int[N
];
int[] cols
= new int[N
];
int[] boxes
= new int[N
];
for (int i
= 0; i
< N
; i
++) {
for (int j
= 0; j
< N
; j
++) {
if (board
[i
][j
] == '.')
continue;
int tmp
= board
[i
][j
] - '0';
int boxIndex
= i
/ 3 * 3 + j
/ 3;
if ((rows
[i
] >> tmp
& 1) == 1
|| (cols
[j
] >> tmp
& 1) == 1
|| (boxes
[boxIndex
] >> tmp
& 1) == 1)
return false;
rows
[i
] = rows
[i
] | (1 << tmp
);
cols
[j
] = cols
[j
] | (1 << tmp
);
boxes
[boxIndex
] = boxes
[boxIndex
] | (1 << tmp
);
}
}
return true;
}
}
转载:
作者:sharonou
链接:https
://leetcode
-cn
.com
/problems
/valid
-sudoku
/solution
/javawei
-yun
-suan
-1ms
-100-li
-jie
-fang
-ge
-suo
-yin
-by
/
转载请注明原文地址:https://blackberry.8miu.com/read-37668.html