编写一个高效的算法来搜索 m x n 矩阵中的一个目标值。该矩阵具有以下特性:
每行中的整数从左到右排序。
每行的第一个整数大于前一行的最后一个整数。
例如,
以下矩阵:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
给定 目标值= 3,返回 true。
详见:https://leetcode.com/problems/search-a-2d-matrix/description/
Java实现:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row=matrix.length-1;
int col=0;
while(row>=0&&col<matrix[0].length){
if(matrix[row][col]==target){
return true;
}else if(matrix[row][col]>target){
--row;
}else{
++col;
}
}
return false;
}
}
C++实现:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int i = matrix.size()-1;
int j = 0;
while (i >=0 && j <matrix[0].size())
{
if (target > matrix[i][j])
{
++j;
}
else if (target < matrix[i][j])
{
--i;
}
else
{
return true;
}
}
return false;
}
};
参考:https://blog.csdn.net/zhangxiao93/article/details/49835511