|
2 | 2 | * // This is the BinaryMatrix's API interface. |
3 | 3 | * // You should not implement it, or speculate about its implementation |
4 | 4 | * interface BinaryMatrix { |
5 | | - * public int get(int x, int y) {} |
| 5 | + * public int get(int row, int col) {} |
6 | 6 | * public List<Integer> dimensions {} |
7 | 7 | * }; |
8 | 8 | */ |
9 | 9 |
|
10 | 10 | class Solution { |
11 | 11 | 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--; |
20 | 22 | } |
21 | 23 | } |
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; |
38 | 25 | } |
39 | 26 | } |
0 commit comments