• code第一部分数组:第十九题 矩阵元素为0,横列置零


    code第一部分数组:第十九题 矩阵元素为0,横列置零

    分析
    O(m + n) 空间的方法很简单,设置两个数组,记录每行和每列是否存在 0。
     
    void zero(int **a, int m, int n){
        bool row[m], col[n];   
        memset(row, false, sizeof(row));
        memset(col, false, sizeof(col));   
        for(int i=0; i<m; ++i)
            for(int j=0; j<n; ++j)
                if(a[i][j] == 0){
                    row[i] = true;
                    col[j] = true;
                }
        for(int i=0; i<m; ++i)
            for(int j=0; j<n; ++j)
                if(row[i] || col[j])
                    a[i][j] = 0;
    }
    
    void setZeroes(vector<vector<int> > &matrix)
    {
        const size_t m = matrix.size();
        const size_t n = matrix[0].size();
        bool row_has_zero = false; // 第一行是否存在 0
        bool col_has_zero = false; // 第一列是否存在 0
        for (size_t i = 0; i < n; i++)
        if (matrix[0][i] == 0)
        {
            row_has_zero = true;
            break;
        }
        for (size_t i = 0; i < m; i++)
        {
            if (matrix[i][0] == 0) {
            col_has_zero = true;
            break;
        }
        for (size_t i = 1; i < m; i++)
        {
            for (size_t j = 1; j < n; j++)
            {
                if (matrix[i][j] == 0)
                {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
    
            }
    
        }
        for (size_t i = 1; i < m; i++)
        {
            for (size_t j = 1; j < n; j++)
            {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                {
                    matrix[i][j] = 0;
                }
            }
        }
        if (row_has_zero)
        {
            for (size_t i = 0; i < n; i++)
            {
                matrix[0][i] = 0;
            }
        }
        if (col_has_zero)
        {
            for (size_t i = 0; i < m; i++)
            {
                matrix[i][0] = 0;
            }
        }
    
    }
  • 相关阅读:
    Codeforce Round #215 Div2 C
    Facebook Hacker Cup 2014 Qualification Round
    Codeforce Round #214 Div2
    Codeforce Round #213 Div2
    FOJ 2013 11 月赛
    Codeforce Round #211 Div2
    Codeforce Round #210 Div2
    如何下载spring-framework
    [转]大型网站系统架构的演化
    sql查询,如何增加一列
  • 原文地址:https://www.cnblogs.com/tao-alex/p/6443054.html
Copyright © 2020-2023  润新知