LeetCode -- Leftmost Column with at Least a One 找出最左边至少有一个1的列

823 阅读1分钟

(This problem is an interactive 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(row, col) returns the element of the matrix at index (row, col) (0-indexed). BinaryMatrix.dimensions() returns a list of 2 elements [rows, cols], which means the matrix is rows * cols. 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.

二进制矩阵(数值为0或者1),每一行是非递减序列,也就是如果中间有1,后面都是1. 找出最左边的,至少有一个1的列。

有两个提示解决办法:

1. 使用二分法

2.从右上角开始遍历矩阵,如果为0,则向下,如果为1,则向左

提示1解法:每次取中间index的所有行,如果都为0,说明符合条件的在右边,否则在左边,时间复杂度为 rows*log(columns):rows为行数,columns为列数

    int rows,columns,result;
    
    public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
        rows = binaryMatrix.dimensions().get(0);
        columns = binaryMatrix.dimensions().get(1);
    
        result = -1;
        binarySearch(binaryMatrix,0,columns-1);
        return result;
    }
    
    void binarySearch(BinaryMatrix binaryMatrix,int si,int ei){
        if(si > ei){
            return;
        }
        int mid = si + (ei - si)/2;
        if(areAllZeros(binaryMatrix,mid)){
            binarySearch(binaryMatrix,mid+1,ei);
        }else{
            result = mid;
            binarySearch(binaryMatrix,si,mid-1);
        }
    }
    boolean areAllZeros(BinaryMatrix binaryMatrix,int index){
        for(int i=0; i<rows; i++){
            if(binaryMatrix.get(i,index) == 1){
                return false;
            }
        }
        return true;
    }

提示2解法:时间复杂度为rows+columns

public int leftMostColumnWithOne(BinaryMatrix binaryMatrix){
    int rows = binaryMatrix.dimensions().get(0);
    int columns = binaryMatrix.dimensions().get(1);
    
    int index = 0;
    int result = -1;
    for(int j=columns-1; j>=0; j--){
        while(index < rows){
            if(binaryMatrix.get(index,j) == 1){
                result = j;
                break;
            }else{
                index++;
            }
        }
    }
    return result;
}