LeetCode 第 73 题 (Set Matrix Zeroes)

来源:互联网 发布:linux tail grep 结合 编辑:程序博客网 时间:2024/04/29 16:49

LeetCode 第 73 题 (Set Matrix Zeroes)

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(mn) 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 元素的位置。记录完所有的零元素的位置后,就可以清零工作了。唯一需要注意的是这一特殊的行和列要最后处理,因为提早把它清零了我们就失去其他零元素的位置信息了。

下面是代码:

void getFirstZerosPos(const vector<vector<int>>& matrix, int &row_, int &col_){    int rows = matrix.size();    int cols = matrix[0].size();    for( int row = 0; row < rows; row++ )    {        for(int col = 0; col < cols; col ++ )        {            if(matrix[row][col] == 0)            {                col_ = col;                row_ = row;                return;            }        }    }    col_ = -1;    row_ = -1;    return;}void setZeroes(vector<vector<int>>& matrix){    int ROWS = matrix.size();    if(ROWS == 0) return;    int COLS = matrix[0].size();    int col0, row0;    getFirstZerosPos(matrix, row0, col0);    if(row0 == -1) return;    for( int row = row0; row < ROWS; row++ )    {        for(int col = 0; col < COLS; col ++ )        {            if(matrix[row][col] == 0)            {                matrix[row][col0] = 0;                matrix[row0][col] = 0;            }        }    }    for(int col = 0; col < COLS; col ++ )    {        if(col == col0) continue;        if(matrix[row0][col] == 0)        {            for(int row = 0; row < ROWS; row++)            {                matrix[row][col] = 0;            }        }    }    for(int row = 0; row < ROWS; row++) //遍历这一列的各行    {        if(row == row0) continue;        if(matrix[row][col0] == 0) //如果这行对应的元素为 0        {            for(int col = 0; col < COLS; col ++ ) //就将这一行全写为 0            {                matrix[row][col] = 0;            }        }    }    for(int row = 0; row < ROWS; row++)    {        matrix[row][col0] = 0;    }    for(int col = 0; col < COLS; col++)    {        matrix[row0][col] = 0;    }}
1 0
原创粉丝点击