矩陣中兩行或者兩列之間的元素的大小并沒有一定的規律,是以二分法不太好用,直接用74. Search a 2D Matrix的解法二即可,時間複雜度為O(n + m),代碼如下:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int i = 0;
int j = cols - 1;
while(i < rows && j >= 0){
if(matrix[i][j] == target){
return true;
}else if(matrix[i][j] < target){
i++;
}else{
j--;
}
}
return false;
}
}