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

topic

In a two-dimensional array of n * m, each row from left to right in order of ascending sort, to sort each column from top to bottom in increasing order. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

Example:
existing matrix multiplied as follows:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, returns true.
Given target = 20, returns false.

 

limit:

0 <= n <= 1000
0 <= m <= 1000

Thinking

With [LeetCode two-dimensional matrix II] 240. The search
according to an array of features, you can start looking from the bottom left or top right corner of the element, if not equal to the target, can directly reduce or find a row of.

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;
    }
};
Published 18 original articles · won praise 86 · views 160 000 +

Guess you like

Origin blog.csdn.net/u013178472/article/details/105107381