原题链接🔗:
难度:中等⭐️⭐️
题目
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例 1:
输入: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
示例 2:
输入: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 = 20
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
每行的所有元素从左到右升序排列
每列的所有元素从上到下升序排列
-109 <= target <= 109
题解
遍历法
- 题解:
从右上角开始搜索:由于矩阵的每一行是递增的,我们可以从右上角的元素开始搜索。这样,如果目标值大于当前元素,我们可以安全地向左移动;如果目标值小于当前元素,我们可以安全地向下移动。
逐步移动:在每一步中,根据目标值与当前元素的比较结果来决定移动方向。
- 如果 target 大于当前元素,向左移动一列。
- 如果 target 小于当前元素,向下移动一行。
边界检查:在移动过程中,需要检查是否超出了矩阵的边界。如果超出了边界, 搜索结束,返回 false。
找到目标:如果在矩阵中找到了目标值,返回 true。
- 复杂度:时间复杂度O(mn),空间复杂度O(1)。
- 过程:
- 首先检查矩阵是否为空或其行是否为空,若是,则返回 false。
- 确定矩阵的行数 rows 和列数 cols。
- 使用两个指针 i 和 j,从矩阵的右上角开始搜索,i 表示行索引,j 表示列索引。
- 使用一个 while 循环进行搜索,当 i 小于行数且 j 大于等于0时继续循环。
- 如果当前元素等于目标值,则返回 true 表示找到目标。
- 如果当前元素大于目标值,则将 j 减1,向左移动。
- 如果当前元素小于目标值,则将 i 加1,向下移动。
- 如果循环结束都没有找到目标值,则返回 false。
- c++ demo:
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix[0].empty()) return false;
int rows = matrix.size();
int cols = matrix[0].size();
int i = 0, j = cols - 1;
while (i < rows && j >= 0) {
if (matrix[i][j] == target) return true;
else if (matrix[i][j] > target) j--;
else i++;
}
return false;
}
};
int main() {
Solution solution;
vector<vector<int>> 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}
};
int target1 = 5, target2 = 20;
cout << (solution.searchMatrix(matrix, target1) ? "Found" : "Not Found") << endl;
cout << (solution.searchMatrix(matrix, target2) ? "Found" : "Not Found") << endl;
return 0;
}
- 输出结果:
Found
Not Found
其他方法
- 二分查找:时间复杂度O(mlogn),空间复杂度O(1)。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (const auto& row: matrix) {
auto it = lower_bound(row.begin(), row.end(), target);
if (it != row.end() && *it == target) {
return true;
}
}
return false;
}
};
- Z 字形查找:时间复杂度O(m+n),空间复杂度O(1)。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
int x = 0, y = n - 1;
while (x < m && y >= 0) {
if (matrix[x][y] == target) {
return true;
}
if (matrix[x][y] > target) {
--y;
}
else {
++x;
}
}
return false;
}
};