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
.
The condition of the first question is stronger than the second one, that is, the first element of our bank is larger than the last element in the previous line. So if the first problem is to flatten the 2D matrix into a 1D list, the list is a sorted list. Can be found again by the dichotomy method.
1 classsolution (object):2 defSearchmatrix (self, Matrix, target):3 """4 : Type Matrix:list[list[int]]5 : Type Target:int6 : Rtype:bool7 """8 if notMatrix:9 returnFalseTen OneNums = [] A forEleminchMatrix: -Nums + =Elem -n =Len (nums) the -Low, high = 0, n-1 - whileLow <=High : -Mid = (Low+high)//2 + ifTarget <Nums[mid]: -High = Mid-1 + elifTarget >Nums[mid]: ALow = mid + 1 at Else: - returnTrue - returnFalse
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 in ascending from left to right.
- Integers in each column is sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, one, a], [2, 5, 8, 3, 6, 9, +, + ], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]]
Given Target = 5
, return true
.
Given Target = 20
, return false
.
The second question does not pull the 2D matrix into a 1D list as in the first question. You can use similar lookup methods in the matrix similar to kth smallest element in a sorted.
1 defSearchmatrix (self, Matrix, target):2 """3 : Type Matrix:list[list[int]]4 : Type Target:int5 : Rtype:bool6 """7M, n =len (Matrix), Len (matrix[0])8I, j = m-1, 09 Ten whileI >= 0 andJ <N: One ifMATRIX[I][J] >Target: AI-= 1 - elifMATRIX[I][J] <Target: -J + = 1 the Else: - returnTrue - returnFalse
Leetcode and 240. Search a 2D matrix I and II