剑指Offer - 二维数组中的查找

剑指Offer - 二维数组中的查找

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        int row=array.size();
        int column=array[0].size();
        bool flag=false;
        
        for(int i=0;i<row;i++){
            for(int j=0;j<column;j++){
                if(array[i][j]==target){
                    flag=true;
                    break;
                }
            }
        }
        return flag;
    }
};

因为矩阵是有序的,可以继续优化:

class Solution {
public:
    bool Find(int target, vector<vector<int> > array) {
        if(array.size()!= 0)
        {
            int row = 0;//从第0行开始查找
            int col = array[0].size()-1;//从每行最后一列元素向前查找
            while(row < array.size() && col >= 0)
            {
                if(array[row][col] == target)
                    return true;
                else if(array[row][col] > target)
                    col--;
                else
                    row++;
            }
             
        }
        return false;
         
    }
};