此题的矩阵和单调矩阵很像,是肯定要用二分的题目,先第一次二分,找到合适的左区间,第二次找到精确数值,要注意mid的判断,是核心。
class Solution {
public:
int bisect(vector<int> &v, int target)
{
int l = 0, r = v.size()-1;
while(l<r)
{
int mid = ceil((l+r)/2.0);
if(target < v[mid])r = mid-1;
else l = mid;
}
return l;
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int m = matrix.size(), n = matrix[0].size();
vector<int> col;
for(auto r: matrix)col.push_back(r[0]);
int r = bisect(col, target);
int t = bisect(matrix[r], target);
if(matrix[r][t] == target)return true;
else return false;
}
};