https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
编写一个高效的算法来搜索 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。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:从左下角开始走 遇到比自己大的数就往右走,遇到比自己的小的数就往上走,否则相等则返回true。如果直到超出边界还没找到则返回false,其实从左下角和右上角走都可以。
//c++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
if (!row) {
return false;
}
int col = matrix[0].size() ;
int i = row - 1;
int j = 0;
while (j < col && i > -1)
{
if (target > matrix[i][j])
{
j++;
}
else if (target < matrix[i][j])
{
i--;
}
else
{
return true;
}
}
return false;
}
};