题目要求:
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.
示例:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
代码实现:
#include<stdafx.h>
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int> > &matrix, int target) {
size_t m=matrix.size();
size_t n=matrix[0].size();
size_t i=0;
size_t j=n-1;
//从右上角开始找,如果target大于此数,二维矩阵往下找,否则往左找
while(j>=0&&i<m)
{
if(matrix[i][j]<target)
{
i++;
}
else if (matrix[i][j]>target)
{
if(j==0)
return false;//此处防止j=0时,j--变成4294967295
j--;
}
else
return true;
}
return false;
}
};
void main()
{
//初始化二维矩阵
vector< vector<int>> matrix(3,vector<int>(4,0));
matrix[0][0]=1;
matrix[0][1]=3;
matrix[0][2]=5;
matrix[0][3]=7;
matrix[1][0]=10;
matrix[1][1]=11;
matrix[1][2]=16;
matrix[1][3]=20;
matrix[2][0]=23;
matrix[2][1]=30;
matrix[2][2]=34;
matrix[2][3]=50;
//第一次验证没有通过的一组
/* vector< vector<int>> matrix(3,vector<int>(1,0));
matrix[0][0]=-11;
matrix[1][0]=-7;
matrix[2][0]=-5;*/
Solution s;
cout<<s.searchMatrix(matrix,-6)<<endl;
getchar();
}