二维数组中查找

问题:

一个二维数组,每一行从左到右,每一列从上到下,都是按递增顺序排列,输入一个二维数组和某个数,判断数组中是否存在这个数

解题思路:

排除行和列
比如从右上角元素出发。先确定列的范围,如果查找数大于当前列的第一行数,那么这一行的所有数都大于查找数,排除,继续查找左边列;确定行范围,在前面列的范围内,如果最右边元素小于查找数,则这一行所有数都小于查找数,排除,继续向下查找行,缩小范围。

同理也可以从左上角,左下角,右下角出发,注意缩小范围的方向,选定参考元素。

参考:

剑指offer 原题,第二章,面试题3

代码:

//
//  main.cpp
//  find_in_2d_array
//
//  Created by LiLingyu on 15/10/19.
//  Copyright © 2015年 LiLingyu. All rights reserved.
//

#include <iostream>
#include <assert.h>
#include <time.h>

bool find_in_2d_array(int *a, int rows, int columns, int number)
{
    bool result = false;

    assert(NULL != a && rows>0 && columns>0);

    int x=columns-1, y=0;
    while (y<rows && x>=0) {
        if (a[y*columns+x]==number) {
            return true;
        }
        else if(a[y*columns+x]>number)
        {
            x--;
        }
        else
        {
            y++;
        }
    }

    return result;
}
static inline int max(int a, int b)
{
    return (a>b)?a:b;
}


int main(int argc, const char * argv[]) {
    // insert code here...
    //std::cout << "Hello, World!\n";
    const int COLUMNS = 4;
    const int ROWS = 4;
    int a[COLUMNS*ROWS];

    srand((unsigned int)time(NULL));


    for (int i=0; i<ROWS*COLUMNS; i++) {
        a[i] = rand()%(ROWS*COLUMNS);
    }

    a[0]=rand()%(COLUMNS*ROWS);
    for (int i=1; i<COLUMNS; i++) {
        a[i] = a[i-1]+rand()%3;
    }

    for (int i=1; i<ROWS; i++) {
        a[i*COLUMNS]=a[(i-1)*COLUMNS]+rand()%3;
    }

    for (int y=1; y<ROWS; y++) {
        for (int x=1; x<COLUMNS; x++) {
            a[y*COLUMNS+x] = max(a[(y-1)*COLUMNS+x],a[y*COLUMNS+x-1])+rand()%3;
        }
    }


    int number = rand()%(ROWS*COLUMNS);

    printf("number: %d\n", number);
    printf("array:\n");
    for (int y=0; y<ROWS; y++) {
        for (int x=0; x<COLUMNS; x++) {
            printf("%d\t", a[y*COLUMNS+x]);
        }
        printf("\n");
    }
    printf("answer:\t");
    printf("%d\n", find_in_2d_array(a, ROWS, COLUMNS, number));

    return 0;
}

代码链接:https://github.com/lilingyu/findIn2dSortArray

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值