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.
在二维数组中找到一个目标元素,矩阵中每一行都是升序排列的,并且每一行的元素都比它的上一行的包含的元素大。如果是一位数组我们很容以就想到用二分查找法,对于这道题,只不过是从m个有序数组中查找一个元素,我们可以用两次二分查找,第一个找到target在哪个组,确定target可能在的组之后,在用一次二分查找遍历这个组。在确定组的时候,如果target大于当前元素时,我们不能直接将left = mid + 1; 我们要检查mid组中最大的元素和target的大小,因为target可能在mid组中。代码如下:
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.
在二维数组中找到一个目标元素,矩阵中每一行都是升序排列的,并且每一行的元素都比它的上一行的包含的元素大。如果是一位数组我们很容以就想到用二分查找法,对于这道题,只不过是从m个有序数组中查找一个元素,我们可以用两次二分查找,第一个找到target在哪个组,确定target可能在的组之后,在用一次二分查找遍历这个组。在确定组的时候,如果target大于当前元素时,我们不能直接将left = mid + 1; 我们要检查mid组中最大的元素和target的大小,因为target可能在mid组中。代码如下:
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) return false;
int m = matrix.length;
int n = matrix[0].length;
int l = 0;
int r = m - 1;
int mid = 0;
while(l <= r) {
mid = l + (r - l) / 2;
if(target == matrix[mid][0])
return true;
if(matrix[mid][0] > target)
r = mid - 1;
else {
if(target > matrix[mid][n - 1])
l = mid + 1;
else
break;
}
}
l = 0;
r = n - 1;
while(l <= r) {
int mmid = l + (r - l) / 2;
if(target == matrix[mid][mmid])
return true;
if(target > matrix[mid][mmid])
l = mmid + 1;
else
r = mmid - 1;
}
return false;
}
}
本文介绍了一种高效的算法,用于在具有特定排序规则的矩阵中搜索目标元素。通过两次二分查找,该算法首先定位目标可能所在的行,然后在该行内进行查找。
405

被折叠的 条评论
为什么被折叠?



