线性查找:
从数组的右上角开始查找,数组当前值比 target 大则下标左移,数组当前值比 target 小则下标下移,如此就能找到 target ,或者跳出循环
class Solution {
public:
bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
if (!matrix.size() || !matrix[0].size()) {
return false;
}
int rows = matrix.size(), cols = matrix[0].size();
int row = 0, col = matrix[0].size() - 1;
while (row < rows && col >= 0) {
int num = matrix[row][col];
if (num == target) {
return true;
}
else if (num > target) {
--col;
}
else {
++row;
}
}
return false;
}
};