题目描述(Medium)
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.
题目链接
https://leetcode.com/problems/search-a-2d-matrix/description/
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
算法分析
方法一:首先选取右上角数字,如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查找的数字,去掉此数字所在列;如果该数字小于要查找的数字,则去掉该数字所在行。重复上述过程直到找到要查找的数字,或者查找范围为空。
方法二:二分法查找。
提交代码(方法一):
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() < 1 || matrix[0].size() < 1) return false;
int rows = matrix.size(), cols = matrix[0].size();
int row = 0, col = cols - 1;
while (row < rows && col >= 0)
{
if (matrix[row][col] < target)
++row;
else if (matrix[row][col] > target)
{
// 去掉这一列及下面的行
--col;
rows = row + 1;
}
else
return true;
}
return false;
}
};
提交代码(方法二):
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.size() < 1 || matrix[0].size() < 1) return false;
const size_t m = matrix.size();
const size_t n = matrix[0].size();
int first = 0, last = m * n - 1;
while (first <= last)
{
int mid = (first + last) >> 1;
int value = matrix[mid / n][mid % n];
if (value == target)
return true;
else if (value < target)
first = mid + 1;
else
last = mid - 1;
}
return false;
}
};