30-Day Leetcoding Challenge Day21

本题最先想到的是暴力解法:但题目对访问矩阵元素的次数做了限制。因此暴力法会报错。

有以下三种思路:

1.每行线性搜索。行遍历。找到每行中第一个为元素1的位置,保存位置中最小的列,break退出当前行。(Wrong Answer)

2.每行二分搜索。对行进行二分查找,找到每行中第一个为元素1的位置,保存位置中最小的列。

3.从右上角开始遍历,如果为1,向左移动,如果为0,向下移动。最后返回列的位置-1

JAVA

/**
 * // 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 {}
 * };
 */

class Solution {
    public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
        int row = binaryMatrix.dimensions().get(0);
        int col = binaryMatrix.dimensions().get(1);
        int res = col;
        for(int i = 0; i < row; i++){
            int left = 0;
            int right = col-1;
            while(left < right){
                int mid = (left+right)/2;
                if(binaryMatrix.get(i, mid) == 0) left = mid+1;
                else right = mid;
            }
            if(binaryMatrix.get(i, left) == 1) res = Math.min(res, left);
        }
        if(res == col) return -1;
        return res;
    }
}

 

class Solution {
    public int leftMostColumnWithOne(BinaryMatrix binaryMatrix) {
        int row = binaryMatrix.dimensions().get(0);
        int col = binaryMatrix.dimensions().get(1);
        int i = 0;
        int j = col-1;
        while(j >= 0 && i < row){
            if(binaryMatrix.get(i, j) == 0) i++;
            else j--;
        }
        if(j == col-1) return -1;
        return j+1;
    }
}

 

 

Python3

# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
#    def get(self, row: int, col: int) -> int:
#    def dimensions(self) -> list[]:

class Solution:
    def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
        row, col = binaryMatrix.dimensions()
        res = col
        for i in range(row):
            left = 0
            right = col-1
            while left < right: #bug,无=号
                mid = (left + right) // 2
                if binaryMatrix.get(i, mid) == 0:
                    left = mid+1
                else:
                    right = mid #bug 无减1
            if binaryMatrix.get(i, left) == 1:
                res = min(res, left)
        if res == col: #bug
            return -1
        return res

 

class Solution:
    def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
        row, col = binaryMatrix.dimensions()
        i = 0
        j = col-1
        while j >= 0 and i < row:
            if binaryMatrix.get(i, j) == 1:
                j -= 1
            else:
                i += 1
        if j == col-1:
            return -1
        return j+1

 

posted @ 2020-04-30 14:49  yawenw  阅读(93)  评论(0编辑  收藏  举报