给你一个满足下述两条属性的?m x n
?整数矩阵:
给你一个整数?target
?,如果?target
?在矩阵中,返回?true
?;否则,返回?false
?。
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 输出:true
示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
方法1:(100%)
public static boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int left = 0;
int right = rows - 1;
if (rows > 1) {
while (left < right) {
int mid = left + (right - left + 1) / 2;
if (target < matrix[mid][0]) {
right = mid - 1;
} else if (target > matrix[mid][0]) {
left = mid + 1;
} else {
return true;
}
}
}
int min = 0;
int max = matrix[0].length - 1;
if (max > 0) {
while (min <= max) {
int newMid = min + (max - min + 1) / 2;
if (target < matrix[left][newMid]) {
max = newMid - 1;
} else if (target > matrix[left][newMid]) {
min = newMid + 1;
} else {
return true;
}
}
} else {
if (target == matrix[0][0]) {
return true;
} else {
return false;
}
}
return false;
}
其他解法:. - 力扣(LeetCode)