码迷,mamicode.com
首页 > 其他好文 > 详细

Search a 2D Matrix

时间:2015-03-12 15:07:06      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

Search a 2D Matrix

 Total Accepted: 35062 Total Submissions: 111591

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


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;
}

Submission Result: Accepted

地址:Search a 2D Matrix

Search a 2D Matrix

标签:

原文地址:http://blog.csdn.net/oimchuan/article/details/44221333

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!