2023.11.22
本题最先想到的是暴力法和二分法,暴力法就不写了,写一下二分法的解法,java代码如下:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int[] row : matrix){
int left = 0;
int right = row.length-1;
while(left <= right){
int mid = (left + right) / 2;
if(row[mid] == target) return true;
else if(row[mid] > target) right = mid-1;
else left = mid + 1;
}
}
return false;
}
}
翻看了下评论区,有个Z字型解法,是从右上角开始遍历,我则从左下角开始遍历,然后当前元素大于target值就往上走,小于target值就往右走,直到走到边界也没找到就返回false,java代码如下:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length-1;
int col = 0;
//从左下角开始搜索
while(row>=0 && col<matrix[0].length){
if(matrix[row][col] == target) return true;
else if(matrix[row][col] > target) row--;
else col++;
}
return false;
}
}