二维数组中的查找

问题描述:

在一个二维数组中,每一行都按照从左到右递增排序,每一列从上到下递增排序。请完成一个函数,

输入这样一个二维数组和一个整数,判断数组中时候含有该整数。

思路分析:

首先选取数组中右上角的数字。如果该数字等于要查找的数字,查找过程结束;如果该数字大于要查

找的数字,剔除这个数字所在的列;如果该数字小于要查找的数字,提出这个数字所在的行。也就是说

如果要查找的数字不在数组的右上角,则每次在查找范围中剔除一行或者一列,这样每一步都可以缩

小查找范围,知道找到该数字或者查找范围为空。

可以用一下数组分析新思考,使问题具体化:

1 2 8 9

2 4 9 12

4 7  10 13

6 8 11 15

参考源码:

bool Find(int *matrix,int rows,int columns,int number)
{
    bool found = false;

    if ((NULL != matrix) && (rows > 0) && (columns > 0))
    {
        int row = 0;
        int column = columns-1;  //开始时指向二维数组右上角的数字
        while ((row < rows) && (column >= 0))
        {
            if (matrix[row*columns + column] == number)
            {
                found = true;
                break;
            }
            else
            {
                if (matrix[row*columns + column] > number)
                {
                    column--;
                }
                else
                {
                    row++;
                }
            }
        }
    }
    return found;
}

测试用例:

int matrix[4][4] = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int number = 0;
cout<<Find(NULL, 4,4,number)<<endl;

思考:

为何要选右上角开始了,因为根据上述数组特性,只有选取右上角每次才能提出一行或者一列

而缩小范围。如果是一个行列都是递减的二维数组,那么就该选取左上角

生命在于折腾,生活就是如此的丰富多彩
原文地址:https://www.cnblogs.com/Mr-Zhong/p/4119032.html