Jianzhi Offer 04. Search in a two-dimensional array (C++) trim route

In an n * m two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete an efficient function, input such a two-dimensional array and an integer to determine whether the array contains the integer.

Example:

The existing matrix is ​​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, return true.
Given target = 20, return false.

limit:

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

Note: This question is the same as the 240 question on the main website: https://leetcode-cn.com/problems/search-a-2d-matrix-ii/

algorithm:

First, we initialize a (row, col) pointer to the lower left corner of the matrix. Then, until the target is found and returns true (or the pointer points to (row, col) outside of the matrix dimension), we perform the following operations: If the value currently pointed to is greater than the target value, we can move one row "up". Otherwise, if the current The value pointed to is less than the target value, you can move a column. It is not difficult to understand why this will never delete the correct answer; because the rows are sorted from left to right, so we know that each value to the right of the current value is more Large. Therefore, if the current value is already greater than the target value, we know that each value to the right of it will be larger. A very similar argument can also be made for the column, so this search method will always find the target in the matrix (if it exists) .

First put the C++ code (the optimal solution), the idea is clear and clear, the interviewer calls the expert directly. This question is the same as the 4th question of Jianzhi offer, the detailed solution can also be moved to Jian4: search in a two-dimensional array. (Byte question bank)
————————————————
Copyright statement: This article is the original article of CSDN blogger "Wu Su", and it follows the CC 4.0 BY-SA copyright agreement. Please attach Link to the original source and this statement.
Original link: https://blog.csdn.net/qq_30457077/article/details/114192468

class Solution {
    
    
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
    
    
        if(matrix.empty() || matrix[0].empty()) return false;
        //获取行列尺寸
        int rowSize = matrix.size(), columnSize = matrix[0].size();
        int row = 0, column = columnSize - 1;
        while(row < rowSize && column >= 0)
        {
    
    
            // 从矩阵的右上角开始匹配,如果匹配到了,返回true
            if(matrix[row][column] == target) return true;
            // 如果值比target小,则说明这一行都比target小,row往下移一行
            else if(matrix[row][column] < target) row ++;
            // 如果值比target大,说明这一列都比target大,column往左移一行
            else column --;
        }
        return false;
    }
};

Complexity analysis

Time complexity: O(n+m).
The key to time complexity analysis is to notice that in each iteration (we do not return true), the row or column will decrease/increase exactly once. Since rows can only be reduced m times and columns can only be increased n times, the loop cannot run more than n+m times before the while loop is terminated. Because all other work is constant, the total time complexity is linear in the sum of matrix dimensions.
Space complexity: O(1), because this method only handles a few pointers, its memory footprint is constant.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114676997