0
点赞
收藏
分享

微信扫一扫

74. Search a 2D Matrix

乱世小白 2022-08-03 阅读 61


Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false

public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
// write your code here
if(matrix == null || matrix.length == 0){
return false;
}

if(matrix[0] == null || matrix[0].length == 0){
return false;
}

int row = matrix.length;
int column = matrix[0].length;

int start = 0, end = row * column - 1;
while(start <= end){
int mid = start + (end - start) / 2;
int number = matrix[mid / column][mid % column];
if(number == target){
return true;
}else if(number > target){
end = mid - 1;
}else{
start = mid + 1;
}
}

return false;

}

}

class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
for(int i = 0; i < matrix.length; i++) {
if(matrix[i].length > 0 && target >= matrix[i][0] && target <= matrix[i][matrix[i].length - 1]) {
return Arrays.binarySearch(matrix[i], target) >= 0 ? true : false;
}
}
return false;
}
}


举报

相关推荐

0 条评论