1.思路
直接从右上角向左下角遍历。
2.程序
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int m = array.size(), n = array[0].size();
int i = 0, j = n-1;
while(i < m && j >= 0){
if(array[i][j] > target) j--;
else if(array[i][j] < target) i++;
else return true;
}
return false;
}
};
int main() {
vector<vector<int> > array(4, vector<int>(4, 0));
int test[4][4] = {{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}};
int target = 5;
for(size_t i = 0; i < array.size(); ++i) {
for(size_t j = 0; j < array[0].size(); ++j) {
array[i][j] = test[i][j];
}
}
Solution s;
cout << s.Find(target, array) << endl;
return 0;
}
3.运行结果