加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

Leetcode 73 Set Matrix Zeroes

发布时间:2020-12-13 21:14:12 所属栏目:PHP教程 来源:网络整理
导读: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 impro

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的做法

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存在每行每列的第1个位置,

由于行列会交叉,因此会当左上角为0时会不知道究竟是行还是列,

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

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; } }



(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读