2133. Check if Every Row and Column Contains All Numbers
use set to check row, then col
class Solution {
public boolean checkValid(int[][] matrix) {
int n = matrix.length;
Set<Integer> set = new HashSet<>();
for (int i = 0 ; i < n; i++) {
for (int j = 0 ; j < n; j++) {
// if there is a number existed, it's wrong!
if (set.contains(matrix[i][j])) {
return false;
}
set.add(matrix[i][j]);
}
set = new HashSet<>();
}
set = new HashSet<>();
for (int j = 0 ; j < n; j++) {
for (int i = 0 ; i < n; i++) {
// if there is a number existed, it's wrong!
if (set.contains(matrix[i][j])) {
return false;
}
set.add(matrix[i][j]);
}
set = new HashSet<>();
}
return true;
}
}
use Xor
T: O(n^2)
S: O(1)
class Solution {
public boolean checkValid(int[][] matrix) {
int n = matrix.length;
for (int i = 0 ; i < n; i++) {
int rowXor = 0; // 逐 row 檢查
int colXor = 0; // 逐 col 檢查
for (int j = 0 ; j < n; j++) {
rowXor ^= matrix[i][j]^(j+1);
colXor ^= matrix[j][i]^(j+1);
}
if (rowXor != 0 || colXor != 0) {
return false;
}
}
return true;
}
}
Last updated