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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]]
Given target = 3
, return true
.
- 在数组中,查找是否存在target这个数
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int i = 0; for(; i < matrixRowSize; i++) { if(matrix[i][matrixColSize - 1] >= target) break; } if(i == matrixRowSize) return 0; for(int j = 0; j < matrixColSize; j++) { if(matrix[i][j] == target) return 1; } return 0;}
- 先查找每行最后一个值,对比target;得到哪行后对比该行
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
.
bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { int i = 0, j = matrixColSize - 1; while(i < matrixRowSize && j >= 0) { if(matrix[i][j] == target) return 1; else if(matrix[i][j] > target) --j; else ++i; } return 0;}
- i代表行,j代表列,选择第一行,最后一列,如果该值大于target则减少一列;否则增加一行,时间为O(m + n)
- 从左下或右上开始比较
- 可以每一行都用二分法查找,或者每一列进行二分查找,时间为m*lg(n),或者n*lg(m)但是当m,n变大是会大于上面的方法