Search a 2D matrix original problem of leetcode problem solving
In a matrix where each row is incremented from left to right, and the first number in the next row is larger than the last digit in the previous row, the target number is determined to exist.
Note the point:
Example:
Input:
matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]target = 3
Output: True
Thinking of solving problems
The matrix from left to right, from top to bottom, is an incremented array, which can be found by binary search. Now just find the array subscript to the matrix mapping relationship can be: i -> [i // n][i % n]
, where I is the subscript in the array, n is the width of the matrix.
AC Source
class solution(object): def Searchmatrix(self, Matrix, target): "" : Type Matrix:list[list[int]]: type Target:int:rtype:bool "" "m = len (matrix) n = Len (matrix[0]) L, h =0, M * N-1 whileL <= h:mid = l + (h-l)//2 ifMatrix[mid//n][mid% n] = = target:return True elifMatrix[mid//n][mid% n] < Target:l = mid +1 Else: H = mid-1 return Falseif__name__ = ="__main__":assertSolution (). Searchmatrix ([[1,2,3], [4,5,6], [7,8,9]],5) ==True assertSolution (). Searchmatrix ([[1,2], [3,4]],4) ==True assertSolution (). Searchmatrix ([[1]],2) ==False
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Search a 2D Matrix