55 搜索二维矩阵 II
1.问题描述
编写一个高效的算法来搜索 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;
}
2.输入说明
首先输入matrix的行数m、列数n,
然后输入m行,每行n个整数。
最后输入一个整数target。
3.输出说明
输出true或false
4.范例
输入
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
5.代码
#include <iostream>
#include <queue>
#include <cstdlib>
#include <cstring>
#include<algorithm>
using namespace std;
int binarySearch(vector<int>nums, int target) //注意,这里不能把int改成bool,否则会报错
{
int low = 0;
int high = nums.size() - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (nums[mid] < target)
low = mid + 1;
else if (nums[mid] > target)
high = mid - 1;
else
return mid;
}
return -1;
}
bool searchMatrix(vector<vector<int> >matrix, int target)
{
//每行进行二分查找
int m = matrix.size();//行数
int n = matrix[0].size();//列数
for (int i = 0; i < m; i++)
{
if (matrix[i][0] > target)//若该行第一个元素大于target,则该行及后面所有行都不用考虑
break;
if (matrix[i][n - 1] < target)//该行最后一个元素值小于target ,则继续搜下行
continue;
int col = binarySearch(matrix[i], target);//对第i行搜索target
if (col != -1)
{
//cout << "col=" << col << endl;
return true;
}
}
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 = searchMatrix(matrix, target);
cout << (res ? "true" : "false") << endl;
return 0;
}