题目来源:https://leetcode.com/problems/search-a-2d-matrix/ 点击打开链接
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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
值存在. 但是这个矩阵有以下特征.
1. 对于每一行, 数值是从左到右从小到大排列的.
2. 对于每一列, 数值是从上到下从小到大排列的.
题目解析: 对于这个给定的矩阵, 我们如果用brute force蛮力解法, 用两个嵌套循环, O(n^2)便可以得到答案.但
是我们需要注意的是这道题已经给定了这个矩阵的两个特性, 这两个特性对于提高我们算法的时间复杂度
有很大帮助, 首先我们给出一个O(n)的解法, 也就是说我们可以固定住右上角或者左下角的元素, 根据递增或者递减
的规律, 我们可以判断这个给定的数值是否存在于这个矩阵当中.
class Solution74{
public:
bool searchMatrix(vector<vector<int>> &matrix, int target){
/*
数组为0,return false
*/
if (matrix.size() == 0){
return false;
}
if (matrix[0].size() == 0){
return false;
}
int row = matrix.size()-1;
int col = 0;
while (row >= 0 && col < matrix[0].size()){
if (target < matrix[row][col]){
--row;
}
else if (target > matrix[row][col]){
++col;
}
else
return true;
}
return false;
}
};
int main()
{
Solution74 solution;
{
vector < vector < int > > vec = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
int target = 21;
if (solution.searchMatrix(vec, target)){
cout << "true" << endl;
}
else
{
cout << "false";
}
}
system("pause");
return 0;
}