题目源自于leetcode。
题目: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 from left to right.
- The first integer of each row is greater than the last integer of the previous row.
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3
, return true
.
思路: 查找问题,二分查找优先。这又是一个杨氏矩阵,可以采用其特殊的查找方法。
代码一:二分查找找出可能存在的行和列。
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int row = matrix.size();
if(row <= 0)
return false;
int col = matrix[0].size();
if(col <= 0)
return false;
if(matrix[0][0] > target)
return false;
int left, right, mid;
left = 0;
right = row-1;
mid = (left+right)/2;
while(left<=right) //二分查找,寻找特定行
{
if(matrix[mid][0] <= target)
left = mid + 1;
else if (matrix[mid][0] > target)
right = mid - 1;
mid = (left+right)/2;
}
int i = left-1;
left = 0;
right = col-1;
mid = (left + right)/2;
while(left <= right) //二分查找,从特定行中寻找target
{
if(matrix[i][mid] == target)
return true;
else if (matrix[i][mid] > target)
right = mid - 1;
else
left = mid + 1;
mid = (left + right)/2;
}
return false;
}
};
代码二:从左上角开始查找。
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
int row = matrix.size();
if(row == 0)
return false;
int col = matrix[0].size();
if(col == 0)
return false;
int i = 0, j = col-1;
while(i<row && j>=0)
{
if(matrix[i][j] == target)
return true;
else if(matrix[i][j] > target)
j--;
else
i++;
}
return false;
}
};