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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30] ]
Given target = 5, return true.
Given target = 20, return false.
public class Solution {
public boolean search(int[][] matrix,int a, int b, int m, int n, int target) {
if(a > m || b > n) return false;
if(matrix[m][n] < target || matrix[a][b] > target) return false;
else if(matrix[m][n] == target || matrix[a][b] == target) return true;
else {
int left_top_row = a, left_top_column = b, right_buttom_row = m, right_buttom_column = n;
int low = left_top_column, high = right_buttom_column;
int row = left_top_row;
while (low <= high) {
int middle = (low + high)/2;
if (matrix[row][middle] == target) return true;
else if (matrix[row][middle] > target) {
high = middle-1;
} else {
low = middle+1;
}
}
if(low < right_buttom_column) {
n = low;
} else {
a += 1;
}
low = left_top_row;
high = right_buttom_row;
int column = left_top_column;
while (low <= high) {
int middle = (low+high)/2;
if (matrix[middle][column] == target) return true;
else if(matrix[middle][column] > target) high = middle-1;
else low = middle + 1;
}
if(low < right_buttom_row) {
m = low;
} else {
b += 1;
}
return search(matrix, a, b, m, n, target);
}
}
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n=matrix[0].length;
return search(matrix,0,0,m-1,n-1,target);
}
}
本文介绍了一种高效的矩阵搜索算法,该算法能在排序的二维矩阵中查找特定的目标值。矩阵的每一行从左到右递增排序,每一列从上到下递增排序。通过递归划分矩阵,逐步缩小搜索范围来提高查找效率。
406

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



