Problem
A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order.
Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1.
You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface:
BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed).
BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m.
Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly.
Constraints:
1 <= mat.length, mat[i].length <= 100
mat[i][j] is either 0 or 1.
mat[i] is sorted in a non-decreasing way.
Solution
思路过程
看到这个题,英文翻译都翻译了好久,终于搞明白是要做什么了╮(╯_╰)╭
又是感觉在玩游戏,要充分利用每一行排过序的性质
- 没有说这个是方阵,注意长和宽
- 因为每行排过序,所以最大值一定在每一行的右边,且最大值只可能为
1
或是0
- 那么就倒过来,思路从右上角到左下角,leftmost是返回值,遇到
1
,leftmost置为该列,继续检索右边的一列;遇到零,检索下一行 - 最好的情况是检测100次(第一行全是
1
),最坏就是检测200次(全是零或是1
在左下角),符合要求前面no more than 1000 calls to BinaryMatrix
- 惯性思维总觉得每行越往下,越有更多的
1
,但其实每行是不相关的,那么,那个最左边的出现过的1
,不一定是在最下面那一列,它可以是任何排布的
代码
java
class Solution {
public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
List<Integer> list=binaryMatrix.dimensions();
int height=list.get(0);
int width=list.get(1);
// list中的第一个是n,第二个是m
System.out.println(height);
System.out.print(width);
width--;
int n=0;
int leftmost=-1;
while(width>=0 && n<height){
if (binaryMatrix.get(n,width)==0){
++n;
}
else{
leftmost=width;
--width;
}
}
return leftmost;
}
}
python
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
dimensions=binaryMatrix.dimensions()
n=dimensions[0]
m=dimensions[1]-1
print(n,m)
height=0
leftmost=-1
while height<n and m>=0:
if binaryMatrix.get(height,m)==0:
height+=1
else:
leftmost=m
m-=1
return leftmost