题目描述:
在一个m行n列的二维数组中,每一行都按照从左到有的递增顺序排列,每一列都按照从上到下递增顺序排列。现输入这样一个二维数组和整数,判断该数组是否含有该整数!
O(m+n)
-
#include<iostream>
-
using namespace std;
-
//const int COL = 4;
-
//const int ROW = 4;
-
bool find(int **array,int Col,int Row,int searchKey)//注意这里的参数传递
-
{
-
int row = 0;
-
int col = Col-1;
-
-
// int compare = array[0][COL-1];
-
while (1)
-
{
-
if (array[row][col] == searchKey)
-
{
-
return true;
-
}
-
else if (array[row][col] > searchKey && row < Row-1)
-
{
-
++row;
-
}
-
else if (array[row][col] < searchKey && col >= 0)
-
{
-
--col;
-
}
-
else
-
return false;
-
}
-
-
}
-
int main()
-
{
-
int COL,ROW;
-
cin >> COL;
-
cin >> ROW;
-
int **a = new int *[ROW];
-
for (int i = 0;i < COL;i++)
-
{
-
a[i] = new int[COL];
-
}
-
for (int i = 0;i < ROW;i++)
-
{
-
for (int j = 0;j < ROW;j++)
-
cin >> a[i][j];
-
}
-
// int a[][4] = {1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
-
cout << find(a,COL,ROW,18)<< endl;
-
return 0;
-
-
}
阅读(1371) | 评论(0) | 转发(0) |