第一题限制了矩阵从左到右,从上到下,而且上一行的最后一个数比下一行的第一个数要小
满足二分的单调性,而且二维的数组下标变成一维数组的下标的公式是arr1[i/m]i%m == arr2[i]
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size(), m = matrix[0].size();
int l = 0, r = m * n - 1;
while (l < r)
{
int mid = l + r >> 1;
if (matrix[mid / m][mid % m] >= target) r = mid;
else l = mid + 1;
}
if (matrix[l / m][l % m] == target) return true;
else return false;
}
};
class Solution {
public:
bool searchArray(vector<vector<int>> array, int target) {
if (array.empty()) return false;
int i = 0, j = array[0].size() - 1;
while (i < array.size() && j >= 0)
{
if (target == array[i][j])
return true;
else if (target > array[i][j])
i ++;
else
j --;
}
return false;
}
};