11.2Search a 2D Matrix II数组
题目描述
给定一个二维矩阵,已知每行每列都是增序,尝试设计个快速搜索一个数字是否在矩阵中存在的算法。输入是一个二维整数矩阵,和一个待搜索整数。输出是一个bool值,表示这个整数是否存在于矩阵中
输入输出样例
Input :
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
Output:True
题解
因为这个二维数组是增序的,行、列都是增序,所以从右上角开始查找是比较合适的。如果当前值大于待搜索值,就左移一位,如果小于待搜索值,就下移动一位。(选左下角也行,反正就是选一面大一面小的,这样便于加减位数)如果最终移动到左下角时仍不等于待搜索值,说明带搜索值不存在于矩阵中。
cpp
#include <iostream>
#include <vector>
using namespace std;
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size();//矩阵尺寸
if (m == 0) {//无矩阵就返回
return false;
}
int i = 0, j = m - 1;
while (i < m && j >= 0) {
if (matrix[i][j] == target) {
return true;
}
else if (matrix[i][j] > target) {
--j;
}
else {
++i;
}
}
return false;
}
int main() {
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 target = 5;
if (searchMatrix(matrix, target)) {
std::cout << "true" << endl;
}
else {
std::cout << "false" << endl;
}
return 0;
}