Find prove safety [Offer] 04- dimensional array of face questions

Thinking

The array features can start searching at the top right or bottom left corner of the element, if not equal to the target, it can be directly reduced in a row or lookup.

Code

Time complexity: O (n + m)
Complexity Space: O (1)

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

Another way

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

Guess you like

Origin www.cnblogs.com/galaxy-hao/p/12300773.html