/*!
* @file 二维数组中的查找.cpp
* @Date: 2018/01/25 20:43
* @author: sicaolong
* @Contact: sicaolong@163.com
* @brief:
1、二维数组的创建
2、从右上角为起始点a[0][n-1],下面的值比上面的值大,左侧的值比其小
若key>a[i][j],向下找row++,否则向左查找col--;
* @TODO:
*/
#include<iostream>
using namespace std;
int ** creat(int m, int n);//构建二维数组
bool find_2D(int **a, int r, int l, int key);//查找
//=============main 函数======================================
//============================================================
int main()
{
int key;//
int m, n;//m行、n列
int **a;
cout << "请输入二维数组的行数m:";
cin >> m;
cout << "请输入二维数组的列数n:";
a = creat(m, n);
cout << "请输入数组的内容:" << endl;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
cout << "二维数组为:" << endl;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
if (find_2D(a, m, n, key))//如果key存在于数组中就输出成功
{
cout << "========查找成功=====" << endl;
cout << key << "存在于二维数组中" << endl;
}
else
{
cout << "=======查找失败=====" << endl;
cout << key << "不存在于二维数组中" << endl;
}
cout << endl;
}
//====================创建一个m行 n列的二维数组===============
//===========================================================
int **creat(int m, int n)
{
int **r;//创建一个二级指针
r = (int **)malloc(m*sizeof(int *));//r为一个指向int**指针
for (int i = 0; i < m; ++i)
{
r[i] = (int *)malloc(n*sizeof(int));//r[i]为一个指向int*的指针
}
return r;//返回创建的二维数组数组
}
//====================在二维数组a中查找key========
//===============================================
bool find_2D(int **a, int m, int n, int key)//m行n列的数组中查找key值
{
bool found = false;
if (a != NULL&&m > 0 && n > 0)
{
int row = 0;
int columns = n - 1;
while (row<m&&columns >= 0)
{
if (a[row][columns] == key)
{
found = true;
break;
}
else if (a[row][columns]>key)
columns--;
else
row++;
}
}
return found;
}
剑指offer 面试题4 二维数组的查找
最新推荐文章于 2022-08-14 10:01:23 发布