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]
]
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.
public class Solution {
public static boolean searchCurrent(int[] row, int target){
int i = 0;
int j = row.length - 1;
while(i <= j){
int index = (i + j) / 2;
if(row[index] == target) return true;
if(row[index] > target){
j = index - 1;
}else{
i = index + 1;
}
}
return false;
}
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int i = 0;
int j = m-1;
while(i <= j){
int index = (i + j) / 2;
if(matrix[index][0] > target){
j = index - 1;
}else{
if(matrix[index][n-1] < target )
i = index + 1;
else return searchCurrent(matrix[index], target);
}
}
return false;
}
}
本文介绍了一种高效的矩阵搜索算法,该算法能在排序矩阵中快速查找指定数值。矩阵特性包括:每行元素从左到右递增排序,且每行首元素大于前一行末元素。文章通过示例展示了算法的具体实现。
397

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



