标签:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3, return true
MySolution :
bool
searchMatrix(int **matrix, int m, int n, int target)
{
//m = 3,n=1;
//matrix[[1,1]],target=0;
//[[-10],
//[-7],
//[-5]], -10
int i;
int j;
int InHalf = 0;
if( m <=0 || n <= 0 )
return false;
if( m <= 1 && n <= 1 )
{
return matrix[m-1][n-1] == target;
}
InHalf = (int)(n/2)-1;
if( n <= 1 )
{
InHalf = 0;
}
if( target < matrix[0][0] || target > matrix[m-1][n-1] )
return false;
for( i = 0; i < m; i++ )
{
if( target >= matrix[i][0] && target <= matrix[i][n-1] )
{
if( target <= matrix[i][InHalf] )/* n/2 */
{
for( j = 0; j <=InHalf; j++ )
{
if( target == matrix[i][j] )
return true;
}
}
else/* target >= matrix[i][InHalf] */
{
for( j = InHalf+1; j <= n-1; j++ )
{
if( target == matrix[i][j] )
return true;
}
}
}
}
return false;
}标签:
原文地址:http://blog.csdn.net/oimchuan/article/details/44221333