题目链接:https://leetcode.com/problems/search-a-2d-matrix-ii/#/description
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
.
思路:从右上角开始遍历,如果matrix[ i ][ j ]<target, 说明该行所有的数都小于target, 则i++ 。如果matrix[ i ][ j ]>target,说明该列所有的数都大于target,则j--。
class Solution{
public:
bool searchMatrix(vector<vector<int>>& matrix,int target)
{
if (matrix.size()==0 || matrix[0].size()==0)
return false;
int rowNum=matrix.size();
int colNum=matrix[0].size();
int i=0,j=colNum-1;
while(i<rowNum && j>-1)
{
if(target==matrix[i][j])
{
return true;
}
else if(target>matrix[i][j])
{
i++;
}
else if(target<matrix[i][j])
{
j--;
}
}
return false;
}
};