Chinaunix首页 | 论坛 | 博客
  • 博客访问: 504452
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1172
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-21 13:40
个人简介

技术改变命运

文章分类

全部博文(184)

文章存档

2020年(16)

2017年(12)

2016年(156)

我的朋友

分类: C/C++

2016-08-24 11:05:07

题目描述:
在一个m行n列的二维数组中,每一行都按照从左到有的递增顺序排列,每一列都按照从上到下递增顺序排列。现输入这样一个二维数组和整数,判断该数组是否含有该整数!
O(m+n)

点击(此处)折叠或打开

  1. #include<iostream>
  2. using namespace std;
  3. //const int COL = 4;
  4. //const int ROW = 4;
  5. bool find(int **array,int Col,int Row,int searchKey)//注意这里的参数传递
  6. {
  7.     int row = 0;
  8.     int col = Col-1;
  9.     
  10. //    int compare = array[0][COL-1];
  11.     while (1)
  12.     {
  13.         if (array[row][col] == searchKey)
  14.         {
  15.             return true;
  16.         }
  17.         else if (array[row][col] > searchKey && row < Row-1)
  18.         {
  19.             ++row;
  20.         }
  21.         else if (array[row][col] < searchKey && col >= 0)
  22.         {
  23.             --col;
  24.         }
  25.         else
  26.             return false;
  27.     }

  28. }
  29. int main()
  30. {
  31.     int COL,ROW;
  32.     cin >> COL;
  33.     cin >> ROW;
  34.     int **a = new int *[ROW];
  35.     for (int i = 0;i < COL;i++)
  36.     {
  37.         a[i] = new int[COL];
  38.     }
  39.     for (int i = 0;i < ROW;i++)
  40.     {
  41.         for (int j = 0;j < ROW;j++)
  42.             cin >> a[i][j];
  43.     }
  44. //    int a[][4] = {1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
  45.     cout << find(a,COL,ROW,18)<< endl;
  46.     return 0;
  47.     
  48. }

阅读(1331) | 评论(0) | 转发(0) |
0

上一篇:linux内核的一点总结

下一篇:内存管理

给主人留下些什么吧!~~