面试题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;
}
分析:从二维数组的右上角开始查找,若找到,则停止;若比该数字大,则放弃该列;若比该数字小,则放弃该行。
代码如下:
// 面试题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;
}
相关文章推荐
- 程序员PC选购
- 大公司最喜欢问的Java集合类面试题
- 黑马程序员——抽象类
- 【剑指offer 面试题27】二叉搜索树与双向链表
- 面试题26:复杂链表的赋值
- 爱奇艺算法工程师面试题(2015年)
- 《程序员的自我修养》读书笔记6
- 黑马程序员---反射
- 黑马程序员--小结
- block面试题
- 史上最全的程序员求职渠道总结
- 细说高级程序员的几个成长阶段
- 对程序员非常重要的24个软技能
- 【面试题】-反转句子
- (剑指Offer)面试题11:数值的整数次方
- 黑马程序员——JAVA String类
- 黑马程序员——JAVA异常
- 黑马程序员——JAVA类和对象
- 黑马程序员—Java反射
- Java7K面试题—银行业务调度系统