问题描述
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.For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target =3, return true.
问题分析
这题的矩阵很有意思,从左往右递增,从上往下递增,相当于一个递增的数组拆成了n行,所以我们用二分查找,先找到target应该在的行,直接二分就行了。
代码实现
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length;
int col = matrix[0].length;
int targetRow = 0;
boolean isExist = false;
for (int i = 0; i < row; i++) {
if (matrix[i][0] <= target && target <= matrix[i][col - 1]) {
isExist = true;
targetRow = i;
break;
}
}
if (isExist == false) return false;
else {
int low = 0;
int high = col - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (matrix[targetRow][mid] == target) return true;
else if (matrix[targetRow][mid] > target) high = mid - 1;
else if (matrix[targetRow][mid] < target) low = mid + 1;
}
return false;
}
}
网友评论