class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int D = matrix.length;
if(D==0) return false;
int R = matrix[0].length-1;
if(R==-1) return false;
for(int i=0;i=matrix[i][0] && target<=matrix[i][R]){
int left = 0;
while(leftmatrix[i][R] || target<matrix[i][left]) return false;
R--;
left++;
}
}else if(target<matrix[i][0]){
return false;
}
}
return false;
}
}
题解做法:想象成一维数组,用二分法的方法。
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
if (m == 0) return false;
int n = matrix[0].length;
// 二分查找
int left = 0, right = m * n - 1;
int pivotIdx, pivotElement;
while (left <= right) {
pivotIdx = (left + right) / 2;
pivotElement = matrix[pivotIdx / n][pivotIdx % n];
if (target == pivotElement) return true;
else {
if (target < pivotElement) right = pivotIdx - 1;
else left = pivotIdx + 1;
}
}
return false;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/sou-suo-er-wei-ju-zhen-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。