前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 73 Set Matrix Zeroes

Leetcode 73 Set Matrix Zeroes

作者头像
triplebee
发布2018-01-12 15:00:41
4770
发布2018-01-12 15:00:41
举报
文章被收录于专栏:计算机视觉与深度学习基础

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

click to show follow up.

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

具体要求为使用较小的空间,开始m+n的做法

代码语言:javascript
复制
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        vector<int> x;
        for(int i=0;i<matrix.size();i++)
            for(int j=0;j<matrix[0].size();j++)
                if(matrix[i][j]==0)
                {
                    x.push_back(i);
                    x.push_back(j);
                }
        for(int i=0;i<x.size();i+=2)
        {
            for(int j=0;j<matrix.size();j++) matrix[j][x[i+1]]=0;
            for(int j=0;j<matrix[0].size();j++) matrix[x[i]][j]=0;
        }
    }
};

在discuss中看到的O(1)做法,将是否有0存在每一行每一列的第一个位置,

因为行列会交叉,因而会当左上角为0时会不知道到底是行还是列,

所以引入col0记录,col0为0表示是第一列产生的0

代码语言:javascript
复制
void setZeroes(vector<vector<int> > &matrix) {
    int col0 = 1, rows = matrix.size(), cols = matrix[0].size();

    for (int i = 0; i < rows; i++) {
        if (matrix[i][0] == 0) col0 = 0;
        for (int j = 1; j < cols; j++)
            if (matrix[i][j] == 0)
                matrix[i][0] = matrix[0][j] = 0;
    }

    for (int i = rows - 1; i >= 0; i--) {
        for (int j = cols - 1; j >= 1; j--)
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;
        if (col0 == 0) matrix[i][0] = 0;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-09-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档