leftmost_column_with_at_least_a_one
1class BinaryMatrix: 2 def get(self, row, col): 3 pass 4 5 def dimensions(self): 6 pass 7 8 9# @leet start 10class Solution: 11 def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: 12 """ 13 This question asks us to find the leftmost column that has at least 14 a one, and each row of the matrix is sorted in non-decreasing order. 15 For this, we can start out at the top right and then move to the bottom 16 left. 17 18 We know that if the curr_row, curr_col is a 1, we can always go left 19 and if it's a 0, we go down. 20 We then return the previous column that we saw. 21 This runs in $O(M+N)$ time. 22 """ 23 m, n = binaryMatrix.dimensions() 24 curr_row, curr_col = 0, n - 1 25 26 while curr_row < m and curr_col >= 0: 27 if binaryMatrix.get(curr_row, curr_col) == 0: 28 curr_row += 1 29 else: 30 curr_col -= 1 31 return curr_col + 1 if curr_col != n - 1 else -1 32 33 34# @leet end 35 36 37def test(): 38 assert 2 + 2 == 4
class
BinaryMatrix:
class
Solution:
11class Solution: 12 def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: 13 """ 14 This question asks us to find the leftmost column that has at least 15 a one, and each row of the matrix is sorted in non-decreasing order. 16 For this, we can start out at the top right and then move to the bottom 17 left. 18 19 We know that if the curr_row, curr_col is a 1, we can always go left 20 and if it's a 0, we go down. 21 We then return the previous column that we saw. 22 This runs in $O(M+N)$ time. 23 """ 24 m, n = binaryMatrix.dimensions() 25 curr_row, curr_col = 0, n - 1 26 27 while curr_row < m and curr_col >= 0: 28 if binaryMatrix.get(curr_row, curr_col) == 0: 29 curr_row += 1 30 else: 31 curr_col -= 1 32 return curr_col + 1 if curr_col != n - 1 else -1
12 def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int: 13 """ 14 This question asks us to find the leftmost column that has at least 15 a one, and each row of the matrix is sorted in non-decreasing order. 16 For this, we can start out at the top right and then move to the bottom 17 left. 18 19 We know that if the curr_row, curr_col is a 1, we can always go left 20 and if it's a 0, we go down. 21 We then return the previous column that we saw. 22 This runs in $O(M+N)$ time. 23 """ 24 m, n = binaryMatrix.dimensions() 25 curr_row, curr_col = 0, n - 1 26 27 while curr_row < m and curr_col >= 0: 28 if binaryMatrix.get(curr_row, curr_col) == 0: 29 curr_row += 1 30 else: 31 curr_col -= 1 32 return curr_col + 1 if curr_col != n - 1 else -1
This question asks us to find the leftmost column that has at least a one, and each row of the matrix is sorted in non-decreasing order. For this, we can start out at the top right and then move to the bottom left.
We know that if the curr_row, curr_col is a 1, we can always go left and if it's a 0, we go down. We then return the previous column that we saw. This runs in $O(M+N)$ time.
def
test():