Leetcode 73. Set Matrix Zeroes

2017-07-02  本文已影响0人  persistent100

题目

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;
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读