剑指offer——二维数组的查找

来源:互联网 发布:江恩正方软件 编辑:程序博客网 时间:2024/06/08 19:52

题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样一个二维数组和一个整数,判断数组中是否含有该函数。

思路:我们根据已经排好序这个出发点出发。首先待查元素x与二维数组b最右上角比较,如果x<b那么这一列都肯定比待查元素x大,所以可以删除这一列,缩小我们的查找范围。如果x>b,那么x肯定比这一行的所有元素都大,所以删除这一行,最后,如果x==b,那么,恭喜你,找到了。然后如此循环下去就能实现功能了。

例如在下列二位数组中查找7

1       2       8       92       4       9       124       7       10      136       8       11      15

算法实现

#include <iostream>using namespace std;bool Find(int * p, int rows, int columns, int number){    bool found = false;    //增加程序健壮性    if (p!=NULL && rows>0&& columns>0)    {        int row = 0;        int column = columns - 1;        while (row <rows && column >= 0)        {            if (p[row*columns+column] == number)            {                found = true;                break;            }            else if (p[row*columns + column] > number)            {                column--;            }            else            {                ++row;            }        }    }    return found;}int main(){    int array[4][4]{        {1,2,8,9},        {2,4,9,12},        {4,7,10,13},        {6,8,11,15}    };    cout << Find((int *)array, 4, 4, 10) << endl;    return 0;}

本篇仅限于笔记使用。

原创粉丝点击