Sword Finger Offer ------------ Search in a two-dimensional array

Insert picture description here

Topic link!

Idea: For
this question, we can start from the condition of the constraint array in the question. Each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom, so that we can start from the upper left corner Start traversal, if the current element is greater than the target, then remove this column; if it is less than, remove this row.

Code:


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

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/115051121