-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCheck if Every Row and Column Contains All Numbers.java
56 lines (41 loc) · 1.55 KB
/
Check if Every Row and Column Contains All Numbers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/
/*
Time Complexity: O(n) where n = number of elements inside matrix
Space Complexity: O(n) where n = size of row and column. Set only recorded elements from row and then column, one at a time.
*/
class Solution {
private boolean areColumnsValid(int[][] matrix, int rowSize, int colSize) {
for (int i = 0; i < rowSize; i++) {
Set<Integer> uniqueElems = new HashSet<>();
for (int j = 0; j < colSize; j++) {
Integer curElem = Integer.valueOf(matrix[j][i]);
if (uniqueElems.contains(curElem)) {
return false;
}
uniqueElems.add(curElem);
}
}
return true;
}
private boolean areRowsValid(int[][] matrix, int rowSize, int colSize) {
for (int i = 0; i < rowSize; i++) {
Set<Integer> uniqueElems = new HashSet<>();
for (int j = 0; j < colSize; j++) {
Integer curElem = Integer.valueOf(matrix[i][j]);
if (uniqueElems.contains(curElem)) {
return false;
}
uniqueElems.add(curElem);
}
}
return true;
}
public boolean checkValid(int[][] matrix) {
int rowSize = matrix.length;
int colSize = matrix[0].length;
if (areRowsValid(matrix, rowSize, colSize)) {
return areColumnsValid(matrix, rowSize, colSize);
}
return false;
}
}