240.Search a 2D Matrix II
240.Search a 2D Matrix II
难度:Medium
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: 每行的元素从左到右升序排列。 每列的元素从上到下升序排列。 示例:
现有矩阵 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]
]
给定 target = 5,返回 true。 给定 target = 20,返回 false。
解决方法:因为都是有序排列,最开始想使用二分法,但是以超时告终。 所以还是要找规律,从数组的右上角看,如果该数字比target大,则该列所有数都比target大,该列可以忽略寻找;如果该数字比target小,则该行所有数都比target小,该行也可以放弃寻找。 从左下角开始判断也是一样的效果。 代码如下:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty() || matrix[0].empty()) return false;
int row=matrix.size();
int col=matrix[0].size();
if(matrix[row-1][col-1]<target) return false;
int rstart=0,cstart=col-1;
while( rstart<row && cstart >= 0)
{
if(matrix[rstart][cstart] == target) return true;
else if(matrix[rstart][cstart] < target) ++rstart;
else --cstart;
}
return false;
}
};
在搜索判断中,如果碰到相等的就跳出循环返回true
,搜索到左下角后,还没找到,返回false
。
Last updated
Was this helpful?