/** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation * interface BinaryMatrix { * public int get(int row, int col) {} * public List<Integer> dimensions {} * }; */classSolution {publicintleftMostColumnWithOne(BinaryMatrix binaryMatrix) {List<Integer> dim =binaryMatrix.dimensions();int m =dim.get(0);int n =dim.get(1);int leftMost = n; // if all 0, at last leftMost will be nfor (int i =0; i < m; i++) {int left =0;int right = leftMost; // this is the key, upbound should be updated each timewhile (left < right) {int mid = (left + right) >>>1;if (binaryMatrix.get(i, mid) ==1) { right = mid; } else { left = mid +1; // cant find 1, keep moving to right part } } leftMost = left; }return leftMost == n ?-1: leftMost; }}
/** * // This is the BinaryMatrix's API interface. * // You should not implement it, or speculate about its implementation * interface BinaryMatrix { * public int get(int row, int col) {} * public List<Integer> dimensions {} * }; */classSolution {publicstaticintleftMostColumnWithOne(BinaryMatrix binaryMatrix) {List<Integer> dim =binaryMatrix.dimensions();int m =dim.get(0);int n =dim.get(1);int res =-1;int rowIndex =0;int colIndex = n-1;while (rowIndex < m && colIndex >=0) {int value =binaryMatrix.get(rowIndex, colIndex);if (value ==1) { res = colIndex; colIndex--; } else { rowIndex++; } }return res; }}