方法一 暴力解法
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
void true_false(vector<vector<int>> vv, int target){
bool bo = false;
//暴力遍历 双重循环
for(auto it:vv){
for(auto iter:it){
if(iter == target) {
bo = true;
}
}
}
if(bo) cout << "true" << endl;
else cout << "false" << endl;
}
};
int main(){
int target = 0;
cin >> target;
//输入二维数组
int value = 0;
int row = 0, column = 0;
cin >> row >> column;
vector<vector<int>> vv;
vector<int> v;
for(int i = 0; i < row; ++i){
for(int j = 0;j < column; ++j){
cin >> value;
v.push_back(value);
}
vv.push_back(v);
v.clear();
}
Solution s;
s.true_false(vv,target);
}
方法二:数组是有序的,一个变量指向最小值,一个指向最大值,如果target比当前值小,i–,如果target比当前值大,j++。利用二分查找
#include <iostream>
#include <vector>
using namespace std;
class Solution{
public:
bool Find(int target, vector<vector<int>> array) {
//优先判断特殊
if(array.size() == 0)
return false;
int n = array.size();
if(array[0].size() == 0)
return false;
int m = array[0].size();
//从最左下角的元素开始往左或往上
//对于左下角的元素而言,右面的元素都比他大,上面的元素都比他小
for(int i = n - 1, j = 0; i >= 0 && j < m; ){
//元素较大,往上走
if(array[i][j] > target)
i--;
//元素较小,往右走
else if(array[i][j] < target)
j++;
else
return true;
}
return false;
}
};
int main(){
int target = 0;
cin >> target;
//输入二维数组
int value = 0;
int row = 0, column = 0;
cin >> row >> column;
vector<vector<int>> vv;
vector<int> v;
for(int i = 0; i < row; ++i){
for(int j = 0;j < column; ++j){
cin >> value;
v.push_back(value);
}
vv.push_back(v);
v.clear();
}
Solution s;
bool temp = s.Find(target,vv);
if(temp == 0) cout << "false";
if(temp == 1) cout << "true";
}