The technique of finding the target value of the matrix

Putting aside the dependence on knowledge and learning is the key to embarking on the broad road of life.

Algorithms covered in this article:


insert image description here

1. Problem-solving skills

  1. First distinguish between matrix and square matrix

  2. Define rows (Row) and columns (Column):

    • rows = matrix.length;
    • cols = martrix[0].length;
  3. Matrix traversal

    for(int i = 0;i < rows;i++){
          
          
    	for(int j = 0; j < cols;j++){
          
          
    		// TODO ![在这里插入图片描述](https://img-blog.csdnimg.cn/487fae0eddd34646b2fa2ff950412335.webp#pic_center)
    
    	}
    }
    

2. Case

This article is mainly used to discuss and summarize the scheme of finding the target element in the processing matrix .

240. Searching Two-Dimensional Matrix II

Write an efficient algorithm to search for a target value target in the mxn matrix matrix.

This matrix has the following properties:

The elements of each row are arranged in ascending order from left to right.
The elements of each column are arranged in ascending order from top to bottom.

as the picture shows:
insert image description here

1. Solution

Using the characteristics of the matrix in the title, select the upper left corner as the starting point to traverse.

Time complexity: O(m+n)

public boolean searchMatrix(int[][] matrix, int target) {
    
    
        // 1. 处理边界
        if(matrix == null || matrix.length == 0){
    
    
            return false;
        }
		// 处理矩阵题目的好规范:优先把行数、列数给统计出来
        int rows = matrix.length;
        int cols = matrix[0].length;
		
		// 选用『左上角』为起始点
        int i = 0;
        int j = cols-1;

        while(i < rows && j >= 0){
    
    
            if(matrix[i][j] == target){
    
    
                return true;
            }

            if(matrix[i][j] < target){
    
    
                i++;
            }else{
    
    
                j--;
            }
        }
        return false;
    }

74. Search 2D Matrix

Write an efficient algorithm to determine whether there is a target value in the mxn matrix.
This matrix has the following properties:

The integers in each row are in ascending order from left to right.
The first integer in each row is greater than the last integer in the previous row.

PS: Note the difference between this question and 240. Searching Two-dimensional Matrix II .
The expansion of this question is an ordered one-dimensional array .

1. Solution one (O(m+n))

The above solution can still solve this problem

public boolean searchMatrix(int[][] matrix, int target) {
    
    
        if(matrix == null || matrix.length == 0){
    
    
            return false;
        }

        int rows = matrix.length;
        int cols = matrix[0].length;

        int i = 0;
        int j = cols- 1;

        while(i < rows && j >= 0){
    
    
            if(matrix[i][j] == target){
    
    
                return true;
            }

            if(matrix[i][j] > target){
    
    
                j--;
            }else{
    
    
                i++;
            }
        }
        return false;
    }
2. Solution 2 (O(log(m) + log(n)) - optimal solution

Haven’t forgotten the knowledge of junior high school: log(m) + log(n) = log(mn)
According to the description of the title, it can be concluded that the matrix is ​​expanded into an incrementally ordered one-dimensional array .
You who are smart must know that when you see order, you must think of BinarySearch .

 public boolean searchMatrix(int[][] matrix, int target) {
    
    
        // 将二维数组看作是一维的
        if(matrix == null || matrix.length == 0){
    
    
            return false;
        }

        int rows = matrix.length;
        int cols = matrix[0].length;

        int left = 0;
        int right = rows * cols - 1;

        while(left <= right){
    
    
            int mid = left + (right-left)/2;

            // 核心:根据mid在一维数组中的位置 推导出其在矩阵中的位置。
            int i = mid / cols;
            int j = mid % cols;

            if(matrix[i][j] == target){
    
    
                return true;
            }

            if(matrix[i][j] < target){
    
    
                left = mid + 1;
            }else{
    
    
                right = mid - 1;
            }
        }

        return false;
    }
1351. Count Negative Numbers in an Ordered Matrix

Given an m * n matrix grid, the elements in the matrix are arranged in non-increasing order whether they are row or column .
Please count and return the number of negative numbers in the grid.

As shown below:
insert image description here

This question still chooses the upper left corner as the starting point, because if a column in the first row is less than 0, it can be concluded that the entire column is less than 0.

solution
 public int countNegatives(int[][] grid) {
    
    
        if(grid == null || grid.length == 0){
    
    
            return 0;
        }
        int rows = grid.length;
        int cols = grid[0].length;

        int i = 0;
        int j = cols-1;

        int result = 0;

        while(i < rows && j >= 0){
    
    
            if(grid[i][j] < 0){
    
    
                result+=(rows-i);
                j--;
            }else{
    
    
                i++;
            }
        }
        return result;
    }

Guess you like

Origin blog.csdn.net/wangcheeng/article/details/124638890