剑指Offer面试题3:二维数组中的查找

书中实现的是从右上角找起的算法,而我是从左下角找起的。如果比左下角数大,则所查找的数都在左下角右边三列内;否则,在左下角上面那三行里。

#include <iostream>
using namespace std;

#define ROW 4
#define COLOMN 4
bool findnum(int matrix[][COLOMN], int row,int colomn, int num)//二维数据作为参数传递时,一定要给出第二维的大小
{
    bool found = false;
    int i = row-1, j = 0;
    while(i >= 0 && j < colomn)
    {
        cout<<matrix[i][j]<<endl;
        if (num == matrix[i][j])
        {
            found = true;
            break;
        }
        if (num < matrix[i][j])
            i = i-1;
        else
            j = j+1;

    }
    return found;
}

int main()
{
    int matrix[ROW][COLOMN]={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COLOMN; j++)
            cout<<matrix[i][j]<<" ";
        cout<<endl;
    }

    bool found = false;
    int num = 0;
    cout<<"pls input the num you want to find: ";
    cin>>num;
    found = findnum(matrix,ROW,COLOMN,num);
    if (found)
        cout<<"find the num it the matrix";
    else
        cout<<"cannot find the num in the matrix";
    return 0;

}


你可能感兴趣的:(二维数组,面试题,剑指offer)