二维数组的查找

来源:互联网 发布:阿里云代码管理系统 编辑:程序博客网 时间:2024/05/16 16:14

剑指offer(1)

二维数组的查找

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
书上给的解法是选取最右上角的元素开始比较,但是否也可以从左下角开始比较?
看到了这个
vector<int> V1[];vector<vector<int>> V2 ;
cout << V1[0].back() << endl;
cout << V2[0].back() << endl;
区别是V1只是数组,而不能增或者减。
class Solution {public:    bool Find(int target, vector<vector<int> > array) {      if(array.empty()) return false;          int rows = array.size();          int columns = array[0].size();          bool found = false;          int x = 0, y = columns - 1;          while(x>=0 && x < rows && y >=0 && y < columns){              if(array[x][y] == target){                  return true;              }              if(array[x][y] > target) y--;              if(array[x][y] < target) x++;          }          return found;      }};


0 0
原创粉丝点击