题目
深度和宽度方向都是递增序列的二维数组,查看目标值是否存在。
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 bool SearchMatrix(int[,] matrix, int target) {
int rows = matrix.GetUpperBound(0);
int columns = matrix.GetUpperBound(1);
//outer loop as row, then loop element for current row
if(matrix.Length==0 || target<matrix[0,0]) return false;
if(exist(matrix,0,target)) return true;
for(int i=1;i<=rows;i++){
if(matrix[i,columns]<target)
continue;
if(exist(matrix,i,target)) return true;
}
return false;
}
private bool exist(int[,] matrix, int rowno, int target){
int columns = matrix.GetUpperBound(1);
int lo=0, hi=columns+1;
while(lo<hi){
int mid = lo + (hi-lo)/2;
if(matrix[rowno,mid]<target)
lo++;
else if(matrix[rowno,mid]>target)
hi--;
else return true;
}
return false;
}
}
改进
用上这个条件,经过仔细观察,看出的规律还是不足以写出精简的逻辑,只好参考牛人的思想,
We start search the matrix from top right corner, initialize the current position to top right corner, if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too. We can rule out one row or one column each time, so the time complexity is O(m+n).
棒极了!
时间复杂度为O(n+m),而不是像上面的算法为nlog(n) 代码见下:
public class Solution {
public bool SearchMatrix(int[,] matrix, int target) {
if (matrix.Length == 0) return false;
int rows = matrix.GetUpperBound(0);
int columns = matrix.GetUpperBound(1);
int row = 0; int column = columns;//setting init value is a tricky
while (row <= rows && column >= 0)
{
if (matrix[row, column] < target) //rid this row
row++;
else if (matrix[row, column] > target) //rid this column
column--;
else return true;
}
return false;
}
}