博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
面试题2:二维数组中的查找
阅读量:6983 次
发布时间:2019-06-27

本文共 1142 字,大约阅读时间需要 3 分钟。

 

查找思路

首先选取数组中右上角的数字。

(1)如果该数字等于要查找的数字,查询过程结束;

(2)如果该数字大于要查找的数字,剔除这个数字所在的列

(3)如果该数字小于要查找的数字,剔除这个数字所在的行

也就是说,如果要查找的数字不在数组的右上角,则每次都在数组的查找范围中剔除一行或一列,这样每一步都可以缩小查找的范围,直到找到要查找的数字,或者查找范围为空。

 说明:当然也可以从左下角开始查找,道理一样;但不能从左上角或右下角开始查找。

 

上述过程如下图所示: 

C++代码:

#include "stdafx.h"#include 
#include
using namespace std;//在rows行*columns列的二维数组p_nArray中查找nFindNum,找到返回ture, 否则返回falsebool IsFind(int *p_nArray, int rows, int columns, int nFindNum){ assert(p_nArray!=NULL && rows>0 && columns>0); if (p_nArray!=NULL && rows>0 && columns>0) { int row = 0; int column = columns - 1; while (row
=0) { if (*(p_nArray + row*columns + column) == nFindNum) { return true; } else if (*(p_nArray + row*columns + column) > nFindNum) { --column; } else { ++row; } } return false; } else { return false; } }int _tmain(int argc, _TCHAR* argv[]){ int nArr[4][4] = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} }; cout << IsFind(*nArr, 4, 4, 7) << endl; cout << IsFind(*nArr, 4, 4, 0) << endl; //对于二维数组,行指针加1跳过一行,列指针加1跳过一个元素 system("pause"); return 0;}

摘自剑指Offer名企面试官精讲典型编程题。

 

你可能感兴趣的文章
Session问题
查看>>
运用 autoconf 和 automake 自动生成 Makefile 实例讲解
查看>>
OpenSSL 之 RSA 相关命令学习笔记
查看>>
GLSL三种修饰符区别与用途(uniform,attribute和varying)
查看>>
python django django-debug-toolbar 加载缓慢,不能使用。
查看>>
操作系之进程调度及算法详解
查看>>
PHPexcel实列
查看>>
Butterknife 的简单使用 和 配合 Butterknife的插件 Zelezny
查看>>
Magento利用input type=”file”上传图片
查看>>
Android音频开发(4):如何存储和解析wav文件
查看>>
Handler延迟事件使用
查看>>
【DG】Oracle 19c使用dbca来搭建物理DG
查看>>
Cython安装
查看>>
StringBuilder 、StringBuffer 、 String
查看>>
brew install php55 报错 clang: error
查看>>
ubuntu18.4 安装swoole 和 php 扩展 swoole
查看>>
pcDuino入门心得+HDMI声音+蓝牙功放
查看>>
面向对象2
查看>>
c++测试题2016-6-2
查看>>
Nginx与Serssion一致性问题
查看>>