查找二维数组中是否存在目标值

在一个二维数组中,该数组满足所有行从左至右递增,所有列满足从上到下递增。给定一目标值Target,若数组中存在该值,则返回true,否则返回false。

分析:
数字所有行从左到右递增,所有行从上到下递增,则每次将目标值与数组右上角的值进行比较,若相等则返回True,若小于该值,则到下一行,若大于该值,则到前一列。

代码如下:

class Solution
{
   public:
      bool findNumber(vector<vector<int>>& matrix,int target)
      {
         if(matrix.empty()) return false;
         int height=matrix.size()-1;
         int width=matrix[0].size()-1;
         int h=0;
         while(h<=height && width>=0)
         {
           if(matrix[h][width]==target) return true;
           else if(matrix[h][width]< target) h++;
           else width--;
         }
         return false;
       }
}
发布了22 篇原创文章 · 获赞 1 · 访问量 346

猜你喜欢

转载自blog.csdn.net/weixin_43086349/article/details/104652711
今日推荐