Source of the topic:
https://leetcode.com/problems/search-a-2d-matrix/
Test Instructions Analysis:
To a MXN matrix, the matrices are arranged according to small to large, i.e. a[i][j] and a[m][n] If i > M is a[i][j]>a[m][n], if i = = m,j > N, then A[i][j]>a[m][n].
Topic Ideas:
Using a binary lookup, first determine the line in that row, and then continue the binary lookup.
Code (Python):
1 classsolution (object):2 defSearchmatrix (self, Matrix, target):3 """4 : Type Matrix:list[list[int]]5 : Type Target:int6 : Rtype:bool7 """8m =len (Matrix)9 ifm = =0:Ten returnFalse Onen =Len (matrix[0]) A ifn = =0: - returnFalse -Mfirst,mlast = 0,m-1 the whileMfirst <Mlast: -Mid = (Mfirst + mlast + 1)//2 - ifMatrix[mid][0] = =Target: - returnTrue + ifMatrix[mid][0] <Target: -Mfirst =Mid + Else: AMlast = mid-1 at Print(Mfirst) -Nfirst,nlast = 0,n-1 - whileNfirst <=Nlast: -Mid = (Nfirst + nlast)//2 - ifMatrix[mfirst][mid] = =Target: - returnTrue in ifMatrix[mfirst][mid] <Target: -Nfirst = mid + 1 to Else: +Nlast = mid-1 - returnFalse
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/5069802.html
[Leetcode] (python): 074-search a 2D Matrix