Algorithm questions daily practice---Day 79: Matrix zeroing

Get into the habit of writing together! This is the 14th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event .

1. Problem description

Given a  m x n matrix, if an element is  0 , set all elements in its row and column to  0  . Please use an in  -place algorithm.

Topic link: Matrix zeroing

Second, the subject requirements

Example 1

2.png

输入: matrix = [[1,1,1],[1,0,1],[1,1,1]]
输出: [[1,0,1],[0,0,0],[1,0,1]]
复制代码

Example 2

3.png

输入: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
输出: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
复制代码

visit

1.数组
2.建议用时15~25min
复制代码

3. Problem Analysis

This is a question that examines the logic of array thinking. For a given array at the beginning, a loop judgment is performed first.

If the position contains 0, then to record this position, what record is used?

We can construct the two arrays separately

vector<int>row(m),col(n);//行、列数组
复制代码

Store 0 position, the data of this entire row and column.

Finally, traverse the row and column where the current element is located. If it is found row[i]或者col[j]to be equal to 1, then set the element to 0.

Fourth, the encoding implementation

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int i,j,p=0,m=matrix.size(),n=matrix[0].size();//初始化数据
        vector<int>row(m),col(n);//行、列数组
        for(i=0;i<m;i++)//遍历求解位置
        {
            for(j=0;j<n;j++)
            {
                if(matrix[i][j]==0)
                {
                    row[i]=col[j]=1;//暂存行、列
                }
            }
        }
        for(i=0;i<m;i++)//之前记录位置的行、列置为0
        {
            for(j=0;j<n;j++)
            {
                if(row[i]||col[j])
                {
                    matrix[i][j]=0;
                }
            }
        }
    }
};

复制代码

5. Test results

4.png

1.png

Guess you like

Origin juejin.im/post/7086405420687818783