思路:从第一行末尾元素进行查找,分别确定行列数(若最末尾元素小于target,则行数+1,若大于target,则列数-1)

Python:

class Solution:
    def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
        try:
            row,col=len(matrix),len(matrix[0])
        except:
            return False
        rows,cols=0,col-1
        while rows<row and cols>=0:
            if rows<row and col>cols>=0:
                if matrix[rows][cols]>target:
                    cols-=1
                elif matrix[rows][cols]<target:
                    rows+=1
                else:
                    return True
        return False

C++:

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int row=matrix.size();
        int col=matrix[0].size();
        if(row==0||col==0){
            return false;
        }
        int i=0;
        int j=col-1;
        while(i<row&&j>=0){
                if(matrix[i][j]>target){
                    j-=1;
                }
                else if(matrix[i][j]<target){
                    i+=1;
                }
                else{
                    return true;
                }
        }
        return false;
    }
};