美文网首页
Leetcode 73. Set Matrix Zeroes

Leetcode 73. Set Matrix Zeroes

作者: persistent100 | 来源:发表于2017-07-02 11:25 被阅读0次

题目

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:
Did you use extra space?A straight forward solution using O(m n) space is probably a bad idea.A simple improvement uses O(m + n) space, but still not the best solution.Could you devise a constant space solution?

分析

给定一个数组,如果某个元素为0,将其整行与整列都改为0.题目提示可以通过常数内存空间就可解决。我是用m+n的数组来表示某行或某列是否需要改为0.
有些人用matrix的第一行与第一列保存该行或该列是否存在0,这样就不需要额外的内存空间了。

void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {
    int rowflag[matrixRowSize],colflag[matrixColSize];
    for(int i=0;i<matrixRowSize;i++)
        rowflag[i]=0;
    for(int j=0;j<matrixColSize;j++)
        colflag[j]=0;
    for(int i=0;i<matrixRowSize;i++)
    {
        for(int j=0;j<matrixColSize;j++)
        {
            if(matrix[i][j]==0)
            {
                rowflag[i]=1;
                colflag[j]=1;
            }
        }
    }
    for(int i=0;i<matrixRowSize;i++)
    {
        for(int j=0;j<matrixColSize;j++)
        {
            if(rowflag[i]==1||colflag[j]==1)
            {
                matrix[i][j]=0;
            }
        }
    }
}

相关文章

网友评论

      本文标题:Leetcode 73. Set Matrix Zeroes

      本文链接:https://www.haomeiwen.com/subject/uvyncxtx.html