Source of the topic
https://leetcode.com/problems/search-a-2d-matrix/
Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted from the left to the right.
- The first integer of each row was greater than the last integer of the previous row.
Test instructions Analysis
Input:a Matrix and a target to query
Output:true or False
Conditions: Find an element in a matrix, notice that the matrix is ordered
Topic ideas
Find out which column to locate in column two, and then double-click the boundary condition.
PS: In fact, directly in the column search, found low-1 less than 0 o'clock, directly return false can be, but the paste code can be ported to the insertion element of the binary ordering inside, in order to unify there is no change.
AC Code (PYTHON)
1 __author__='YE'2 3 classsolution (object):4 defSearchmatrix (self, Matrix, target):5 """6 : Type Matrix:list[list[int]]7 : Type Target:int8 : Rtype:bool9 """Tenm =len (Matrix) Onen =Len (matrix[0]) ALow =0 -High = M-1 - the whileLow <=High : -Mid = (low + high)/2 - ifMatrix[mid][0] = =Target: - returnTrue + elifMatrix[mid][0] >Target: -High = Mid-1 + Else: ALow = mid + 1 atrow = Low-1 - ifRow <0: -row =0 - -Low =0 -High = N-1 in - whileLow <=High : toMid = (low + high)/2 + ifMatrix[row][mid] = =Target: - returnTrue the elifMatrix[row][mid] >Target: *High = Mid-1 $ Else:Panax NotoginsengLow = mid + 1 - returnFalse the +Matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,50]] Atarget = 16 the Print(Solution (). Searchmatrix (Matrix,target))
[Leetcode] (python): 074-search a 2D Matrix