title :
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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [Ten, One,], [23, 30, 34, 50]]
Given target = 3
, return true
.
code : OJ Test via runtime:75 ms
1 classSolution:2 #@param Matrix, a list of lists of integers3 #@param target, an integer4 #@return A Boolean5 defsearchinline (self, line, target):6Start =07end = Len (line)-18 whileStart <=End:9 ifStart = =End:Ten return[False,true] [line[start]==Target] One ifStart+1 = =End: A ifLine[start]==targetorline[end]==Target: - returnTrue - Else: the returnFalse -Mid= (start+end)/2 - ifline[mid]==Target: - returnTrue + elifLine[mid]>Target: -End = Mid-1 + Else : AStart = Mid+1 at - defSearchmatrix (self, Matrix, target): - ifLen (Matrix) = =0: - returnFalse - - ifLen (Matrix) = = 1 : in returnSelf.searchinline (matrix[0], target) - to ifLen (Matrix) = = 2 : + returnSelf.searchinline ([matrix[1],matrix[0]][matrix[1][0]>target], target) - theStart =0 *end = Len (matrix)-1 $ whileStart <=End:Panax Notoginseng ifStart = =End: - returnself.searchinline (matrix[start],target) the ifStart+1 = =End: + ifMATRIX[START][0] <= Target andMatrix[end][0] >Target: A returnself.searchinline (matrix[start],target) the ifMatrix[end][0] <Target: + returnself.searchinline (matrix[end],target) -Mid = (start+end+1)/2 $ ifMATRIX[MID][0] <= Target andMatrix[mid+1][0] >Target: $ returnself.searchinline (matrix[mid],target) - elifMatrix[mid][0] >Target: -End = Mid-1 the Else : -Start = Mid+1
Ideas :
Search by row Two, then by column two points.
Code writing is cumbersome.
Leetcode "Search a 2D Matrix" Python implementation