思路:
- 将二维数组看成一个一维数组,数组长度为m*n,对于位置x,它映射到matrix数组里面的位置为i/n,i%n,然后利用二分查找即可。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0) return false;
int m = matrix.size();
int n = matrix[0].size();
int lo = 0;
int hi = m*n-1;
int mid,midi,midj;
while(lo <= hi){
mid = (lo + hi) / 2;
midi = mid / n;
midj = mid % n;
if(matrix[midi][midj] == target) return true;
else if(matrix[midi][midj] > target){
hi = mid - 1;
}else{
lo = mid + 1;
}
}
return false;
}
};