LeetCode:Leftmost Column with at Least a One

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. 没有说这个是方阵,注意长和宽
  2. 因为每行排过序,所以最大值一定在每一行的右边,且最大值只可能为1或是0
  3. 那么就倒过来,思路从右上角到左下角,leftmost是返回值,遇到1,leftmost置为该列,继续检索右边的一列;遇到零,检索下一行
  4. 最好的情况是检测100次(第一行全是1),最坏就是检测200次(全是零或是1在左下角),符合要求前面 no more than 1000 calls to BinaryMatrix
  5. 惯性思维总觉得每行越往下,越有更多的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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值