Day21-Leftmost Column with at Least a One
问题描述:
(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(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.
上面是原问题描述,其实就是给了一个二维矩阵,这个矩阵它们封装了两个函数,一个返回矩阵的维度,另一个返回指定位置的元素值。这个矩阵的特点是每一行都是递增的由0,1组成。而题目要求我们从这个矩阵中找到左边的1所处的列号(从0开始)。
这个题目要求我们不能调用太多次访问元素的那个函数,也就是我们不能用遍历所有元素的暴力解法(头铁不信邪第一次写的就是for循环遍历暴力解法, 结果能找到解,但是超时了,不能通过。)
解法一:
既然暴力解法通过不了,就要利用题目中的性质,每一行都是升序的,又是个查找问题,可以想到用二分搜索的方式检测。首先获得列的中间检索位置,然后遍历每一行的中间值,如果每一行的中间值都为0,而且行升序,说明如果有1肯定在右边啊,反之则在左边。其实就简化为一个简单的二分搜索问题了,只不过添加了检查每一行的中间值这一个步骤。
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x: int, y: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
M,N = binaryMatrix.dimensions()#获取行,列
print(M,N)
start,end = 0,N - 1
while start <= end:
flag = False
mid = (start + end) // 2
for i in range(M):
if binaryMatrix.get(i,mid):
flag = True
break
if flag:
end = mid - 1
else:
start = mid + 1
if start == N:
return -1
return start
#这种的时间复杂度为O(m * lg(n))
#根据提示二还有一种时间复杂度为O(n + m)的
解法二:
根据提示中所说可以用一种O(n + m)时间复杂度的解法,我们从右上角开始遍历,如果遇到0则则说明当前行已经不可能有1了,则我们向下移动,如果遇到1,则可能前面列还有1,我们往左移动,直到到达最后一行或者第一列。
# """
# This is BinaryMatrix's API interface.
# You should not implement it, or speculate about its implementation
# """
#class BinaryMatrix(object):
# def get(self, x: int, y: int) -> int:
# def dimensions(self) -> list[]:
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
M,N = binaryMatrix.dimensions()#获取行,列
print(M,N)
row = 0#从右上角开始
col = N - 1
result = -1
while row < M and col >= 0:
print(row,col)
if binaryMatrix.get(row,col):
result = col
col -= 1
else:
row += 1
return result
#这种的时间复杂度为O(m * lg(n))
#根据提示二还有一种时间复杂度为O(n + m)的
本文探讨了一个互动问题,即在一个行排序的二进制矩阵中寻找最左侧包含1的列。提供了两种解决方案,一是使用二分搜索,二是采用从右上角开始的线性扫描方法。详细解释了每种方法的实现过程和时间复杂度。
143

被折叠的 条评论
为什么被折叠?



