-
Notifications
You must be signed in to change notification settings - Fork 16
/
SpecialPositionInABinaryMatrix.java
51 lines (45 loc) · 1.64 KB
/
SpecialPositionInABinaryMatrix.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
// https://leetcode.com/problems/special-positions-in-a-binary-matrix
// T: O(n * m)
// S: O(n + m)
import java.util.Arrays;
public class SpecialPositionInABinaryMatrix {
public int numSpecial(int[][] matrix) {
final int[] rowSum = getRowSum(matrix);
final ColumnSumData columnSumData = getColumnSum(matrix);
final int[] columnSumOneRowIndex = columnSumData.oneIndex;
final int[] columnSum = columnSumData.sum;
int specialPositions = 0;
for (int i = 0 ; i < columnSum.length ; i++) {
if (columnSum[i] == 1 && rowSum[columnSumOneRowIndex[i]] == 1) {
specialPositions++;
}
}
return specialPositions;
}
private int[] getRowSum(int[][] matrix) {
final int[] sum = new int[matrix.length];
for (int i = 0 ; i < sum.length ; i++) {
sum[i] = Arrays.stream(matrix[i]).sum();
}
return sum;
}
private ColumnSumData getColumnSum(int[][] matrix) {
final int[] sum = new int[matrix[0].length];
final int[] indexes = new int[sum.length];
for (int i = 0 ; i < sum.length ; i++) {
for (int row = 0 , index = 0 ; row < matrix.length ; row++) {
sum[i] += matrix[row][i];
if (matrix[row][i] == 1) indexes[i] = row;
}
}
return new ColumnSumData(sum, indexes);
}
private static final class ColumnSumData {
private final int[] sum;
private final int[] oneIndex;
private ColumnSumData(int[] sum, int[] oneIndex) {
this.sum = sum;
this.oneIndex = oneIndex;
}
}
}