题解 | #二维数组中的查找#
二维数组中的查找
https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
// 搜索空间的检索
// 双指针
int row = array.size();
int col = array[0].size();
int i = 0, j = col - 1;
while(i >= 0 && i < row && j >=0 && j < col) {
if(i >= 0 && i < row && j >=0 && j < col) {
cout <<"array[i][j] = " << array[i][j] << " i = " << i << " j = " << j << endl;
if(array[i][j] == target) {
return true;
}else if(array[i][j] > target) {
j--;
}else {
i++;
}
}else {
return false;
}
}
return false;
}
};
int main() {
/*
* 7,
* [[1,2,8,9],[2,4,9,12],[4,7,10,13],[6,8,11,15]]
*/
// std::cout << "Hello, World!" << std::endl;
Solution solution;
int target = 3;
// cin >> target;
vector<vector<int>> array = {{1,2,8,9}, {2,4,9,12}, {4,7,10,13}, {6,8,11,15}};
cout << solution.Find(target, array) << endl;
return 0;
}
经典写法:双指针!
查看14道真题和解析