题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
class Solution { public: bool Find(int target, vector<vector<int> > array) { int rows = array.size(); // 获取行数 int cols = array[0].size(); // 获取列数 if ( rows == 0) // 特殊情况判断 return false; int cur_row = 0; int cur_col = cols - 1; while ( cur_row < rows && cur_col >= 0) { int cur_num = array[cur_row][cur_col]; //从右上角的元素开始搜索 if (cur_num == target) // 如果相等,则返回真 return true; else if (cur_num < target) // 如果当前的值小于目标值,则删除这一行,搜索范围从下一行开始 cur_row++; else // 如果当前的值大于目标值,则删除这一列, cur_col--; } return false; } };