Skip to content

Create 002 #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 17, 2023
Merged

Create 002 #1

merged 1 commit into from
Jan 17, 2023

Conversation

rongweihe
Copy link
Owner

test

@rongweihe
Copy link
Owner Author

rongweihe commented Jan 17, 2023

面试题 01.08. 零矩阵
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        //思路
        //1.动态记录第一行和第一列是否需要全部置为零,作为标记数组
        //2.遍历矩阵,标记数组
        //3.跟进标记数组来重新对矩阵赋值
        //4.重新处理第一行和第一列
        if (matrix.size() == 0 || matrix[0].size() == 0) return;
        bool row = false, col = false;
        for(int i = 0; i < matrix.size(); ++i) {
            for(int j = 0; j < matrix[0].size(); ++j) {
                if(matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                    if(i == 0) row = true;
                    if(j == 0) col = true;
                }
            }
        }
        for(int i = 1; i < matrix.size(); ++i) {
            if(matrix[i][0] == 0) {
                for(int j = 1; j < matrix[0].size(); ++j) {
                    matrix[i][j] = 0;
                }
            }
        }
        for(int i = 1; i < matrix[0].size(); ++i) {
            if(matrix[0][i] == 0) {
                for(int j = 1; j < matrix.size(); ++j) {
                    matrix[j][i] = 0;
                }
            }
        }
        if(row) {
            for(int i = 0; i < matrix[0].size(); ++i) {
                matrix[0][i] = 0;
            }
        }
        if(col) {
            for(int i = 0; i < matrix.size(); ++i) {
                matrix[i][0] = 0;
            }
        }
    }
};

@rongweihe rongweihe merged commit a71b6dc into master Jan 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant