[LeetCode sword refers to offer04] Search in two-dimensional array (simple math)

1. The topic

insert image description here

2. Ideas

From left to right, from top to bottom, the two paths are arranged in numerical order from small to large. In order to determine targetwhether it exists, you can start from a different starting point, such as from the upper right corner (in fact, it is also possible to start from the lower left corner). At this time, it is very magical now:

  • If the current value is larger than the current value target, you cannot continue to go down (it will only get bigger and bigger), and if you go to the left, the value will become smaller, and it will be closer to the possible target;
  • If the current value is targetsmaller than the current value, you cannot go to the left (it will only get smaller and smaller), and if you go down, the value will become larger, and it will be closer to the possible target.

In addition, pay attention to the details. At the beginning, it is judged whether matrixthe two-dimensional array is empty. If it is empty, then taking the number of columns matrix.size() == 0at this time matrix[0].size()will report an error out of bounds, so don't take the number of rows and columns first and then judge the empty.

3. Code

class Solution {
    
    
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
    
    
        if(matrix.size() == 0 || matrix[0].size() == 0) return false;
        int row = matrix.size(), col = matrix[0].size();
        //设置初始点在右上角
        int i = 0, j = col - 1;
        while(i <= row - 1 && j >= 0){
    
    
            if(matrix[i][j] == target){
    
    
                return true;
            }else if(matrix[i][j] > target){
    
    
                //往左边走
                j--;
            }else{
    
    //当前值小于目标值时,不能往左边走了,否则更小
                //往下走
                i++;
            }
        }
        return false;
    }
};

Guess you like

Origin blog.csdn.net/qq_35812205/article/details/123607307