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.
[ [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] ]
这题一开始想用从左到右,再上到下的方法去实现,但是不行,后来看了别人的实现,应该使用的是先取右上的元素与target进行比较,如果大于target的话那么这一列都不会存在target,小于的话那么改行都不会存在该元素,从而进行下一步的搜寻,代码如下:
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int>>& matrix, int target) { 4 if(!matrix.size() || !matrix[0].size()) 5 return false; 6 int rowCount = matrix.size(); 7 int colCount = matrix[0].size(); 8 for(int i = 0, j = colCount - 1; i < rowCount && j >= 0; ){ 9 if(matrix[i][j] == target) return true; 10 else if(matrix[i][j] > target) 11 j--; 12 else 13 i++; 14 } 15 return false; 16 } 17 };