Skip to content

Commit 0eb294b

Browse files
authored
Update Leftmost Column with at Least a One.java
1 parent 7518ae0 commit 0eb294b

File tree

1 file changed

+12
-25
lines changed

1 file changed

+12
-25
lines changed

Medium/Leftmost Column with at Least a One.java

Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,38 +2,25 @@
22
* // This is the BinaryMatrix's API interface.
33
* // You should not implement it, or speculate about its implementation
44
* interface BinaryMatrix {
5-
* public int get(int x, int y) {}
5+
* public int get(int row, int col) {}
66
* public List<Integer> dimensions {}
77
* };
88
*/
99

1010
class Solution {
1111
public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
12-
List<Integer> dims = binaryMatrix.dimensions();
13-
int rows = dims.get(0);
14-
int cols = dims.get(1);
15-
int minIdx = Integer.MAX_VALUE;
16-
for (int i = 0; i < rows; i++) {
17-
int idx = binarySearch(binaryMatrix, i, 0, cols - 1);
18-
if (idx != -1) {
19-
minIdx = Math.min(minIdx, idx);
12+
List<Integer> dimension = binaryMatrix.dimensions();
13+
int numRows = dimension.get(0);
14+
int numCols = dimension.get(1);
15+
int currRow = 0;
16+
int currCol = numCols - 1;
17+
while (currRow < numRows && currCol >= 0) {
18+
if (binaryMatrix.get(currRow, currCol) == 0) {
19+
currRow++;
20+
} else {
21+
currCol--;
2022
}
2123
}
22-
return minIdx == Integer.MAX_VALUE ? -1 : minIdx;
23-
}
24-
25-
private int binarySearch(BinaryMatrix binaryMatrix, int row, int start, int end) {
26-
int minIdx = Integer.MAX_VALUE;
27-
while (start <= end) {
28-
int mid = (start + end) / 2;
29-
if (binaryMatrix.get(row, mid) == 1) {
30-
minIdx = Math.min(minIdx, mid);
31-
end = mid - 1;
32-
}
33-
else {
34-
start = mid + 1;
35-
}
36-
}
37-
return minIdx == Integer.MAX_VALUE ? -1 : minIdx;
24+
return currCol == numCols - 1 ? -1 : currCol + 1;
3825
}
3926
}

0 commit comments

Comments
 (0)