搜索二维矩阵 II
作者: Turbo
时间限制: 1s
章节: 二分查找
问题描述
编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。要求使用二分查找。
该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
说明:以上所说的升序,由于中间存在重复元素,因此严格来说,"升序"应该理解成"非递减"
示例:
现有矩阵 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。
给定 target = 20,返回 false。
可使用以下main函数:
int main()
{
vector<vector<int> > matrix;
int target;
int m,n,e;
cin>>m;
cin>>n;
for(int i=0; i<m; i++)
{
vector<int> aRow;
for(int j=0; j<n; j++)
{
cin>>e;
aRow.push_back(e);
}
matrix.push_back(aRow);
}
cin>>target;
bool res=Solution().searchMatrix(matrix,target);
cout<<(res?"true":"false")<<endl;
return 0;
}
5 5
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
5
true
从右上角 (0, n-1) 出发,规则是:
-
如果
当前值 > target→ 向左走(col--) -
如果
当前值 < target→ 向下走(row++) -
如果相等 → 返回
true
最坏情况下 ,你最多向左走 n-1 步,向下走 m-1 步,加起来就是 (m-1) + (n-1) = m + n - 2 步。
所以时间复杂度是 O(m + n),这是线性复杂度,不是对数复杂度。
cpp
# include<bits/stdc++.h>
using namespace std;
class Solution{
public:
bool searchMatrix(vector<vector<int> >& v,int target){
int m = v.size();
if(m==0) return 0;
int n = v[0].size();
int i = 0;
int j = n - 1;
while(i<m&&j>=0){
if(v[i][j]==target) return true;
if(target>v[i][j]) i++;
else j--;
}
return false;
}
};
int main()
{
vector<vector<int> > matrix;
int target;
int m,n,e;
cin>>m;
cin>>n;
for(int i=0; i<m; i++)
{
vector<int> aRow;
for(int j=0; j<n; j++)
{
cin>>e;
aRow.push_back(e);
}
matrix.push_back(aRow);
}
cin>>target;
bool res=Solution().searchMatrix(matrix,target);
cout<<(res?"true":"false")<<endl;
return 0;
}