时间限制:1秒 空间限制:32768K 热度指数:500065
本题知识点: 查找

题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

class Solution {
public:
    bool Find(int target, vector<vector<int> > array)
    {
        int rowCount = array.size();
        int colCount = array[0].size();
        int row = 0;  
        int line = colCount-1;  
        while(row<rowCount&&line>=0)  
          {  
             if(array[row][line]==target)  
                 return true;  
              else if(array[row][line]<target)  
                    row++;  
                else  
                    line--;  
             }  
            return false;  
    }  
};
class Solution {
public:
    bool Find(int target, vector<vector<int> > array)
    {
        int rowCount = array.size();
        int colCount = array[0].size();
        int row = rowCount -1;  
        int line = 0;  
        while(row >= 0 &&line < colCount)  
          {  
             if(array[row][line]==target)  
                 return true;  
              else if(array[row][line]<target)  
                    line++;  
                else  
                    row--;  
             }  
            return false;  
    }  
};

先从第一行最大值比较,如果比目标值小就增行,如果比目标值大就减列;

反过来增列减行也行;
先从第一列的末行最大值开始,如果比目标值小就增列,如果比目标值大就减行;

方法二:二分法查找遍历每一行

class Solution {
public:
    bool Find(int target, vector<vector<int> > array)
    {
        int rowCount = array.size();
        int colCount = array[0].size();
        int low = 0;
        int high = colCount - 1;
        if (array.size() == 0)
        {
            return 0;
        }
        for (int i = rowCount -1;i >=0  ; i--)
        {
             int low = 0;
             int high = colCount - 1;
            while(low<=high)
            {
                int mid=(low+high)/2;
                if(target>array[i][mid])
                    low=mid+1;
                else if(target<array[i][mid])
                    high=mid-1;
                else
                    return true;
            }

         }  
         return false;
    }
};

二分法查找遍历每一列:

class Solution {
public:
    bool Find(int target, vector<vector<int> > array)
    {
        int rowCount = array.size();
        int colCount = array[0].size();
        if (array.size() == 0)
        {
            return 0;
        }
        for (int i = colCount -1;i >=0  ; i--)
        {
             int low = 0;
             int high = rowCount - 1;
            while(low<=high)
            {
                int mid=(low+high)/2;
                if(target>array[mid][i])
                    low=mid+1;
                else if(target<array[mid][i])
                    high=mid-1;
                else
                    return true;
            }

         }  
         return false;
    }
};