Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target = 5
, return true
.
Given target = 20
, return false
.
Solution:
1. 1st idea use one binary search
iterate every rows , binary search from row i to find the insertion position p (bisect_right)
m = len(matrix), n = len(matrix[0]) time complexity O(m*logn)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 if len(matrix) == 0 or len(matrix[0]) == 0: 2 return False 3 i = 0 4 while (i < len(matrix)): 5 pos = bisect_right(matrix[i], target) #use binary search 6 #print(" aaas: ",i, pos-1) 7 if matrix[i][pos-1] == target: 8 return True 9 i += 1 10 return False
2. 2nd utilize the ordered row and column, start from bottom left value v, if v is bigger than target, then go the upper column, else go the right row. time complexity o(m+n)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 if len(matrix) == 0 or len(matrix[0]) == 0: 2 return False 3 m = len(matrix) 4 n = len(matrix[0]) 5 i = m-1 #row 6 j = 0 #column 7 while ( i >= 0 and j <= n-1): 8 if matrix[i][j] == target: 9 return True 10 elif matrix[i][j] > target: 11 i -= 1 12 else: 13 j += 1 14 return False
3. we can also use divide and conquer:
reference: