您的位置:首页 > 职场人生

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

2015-07-08 21:42 441 查看
题目:在二维数组中,每行、每列的数字递增,判断一个数字是否存在

分析:从二维数组的右上角开始查找,若找到,则停止;若比该数字大,则放弃该列;若比该数字小,则放弃该行。

代码如下:

// 面试题3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#define MAXN 100

bool Find(int* matrix,int n,int m,int number)
{
bool found = false;
if(matrix != NULL && n > 0 && m > 0)
{
int row = 0;
int column = m-1;

while(row < n && column >= 0)
{
if(matrix[row*m + column] == number)
{
found = true;
break;
}
else if(matrix[row*m + column] > number)
{
column--;
}
else
{
row++;
}
}
}
return found;
}

int main(int argc, char* argv[])
{
int matrix[4][4]={1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
int n,m,i,j,number;

while(scanf("%d%d",&n,&m)!=EOF){
scanf("%d",&number);
bool found = Find((int*)matrix,n,m,number);
printf("%d\n",found);
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: