105. Set Matrix Zeroes
来源:互联网 发布:机械能守恒实验带数据 编辑:程序博客网 时间:2024/05/21 14:08
-73. Set Matrix Zeroes My Submissions QuestionEditorial Solution
Total Accepted: 68160 Total Submissions: 202122 Difficulty: Medium
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
注意,这里仅仅针对原矩阵,所以说,你将该矩阵复制下,O(mn) space
1.遍历行,看该行有0否,有0该行设为0
2.遍历列,看该列有0否,有则该列设为0
本题要求你用常数空间来做!!!
再想想,将每行是否有0保存在第一列,将每列是否有0保存在第一行,
这样通过,第一行和第一列来进行 行列置0,注意如果
你先对行遍历操作(或者列操作),那么此时你改变了第一列,对列遍历操作时你就不知道第一列是否有0 了。。
所以次点的方法便是保存原矩阵的一行或者一列(取决于你的顺序)
再想想能否有常数空间
有的,我们在遍历行列时,就可以先记录下第一行和第一列是否为0,那么后面便可特殊性的对第一行或者第一列赋值
本题更注重考察你对在限定空间情况下处理问题的能力,本算法时间耗费是大的
class Solution {public: void setZeroes(vector<vector<int>>& matrix) { int m=matrix.size(); if(m==0)return; int n=matrix[0].size(); int col=1,row=1,fircol=1,firow=1; int firone = matrix[0][0]; for(int i=0;i<m;++i){//检测每一行是否有0 row=1; if(matrix[i][0]==0)fircol=0; for(int j=0;j<n;++j) if(matrix[i][j]==0)row=0; if(row==0)matrix[i][0]=0; } if(matrix[0][0]==0)firow=0; for(int i=1;i<n;++i){ //检测每一列是否为0 col=1; for(int j=0;j<m;++j) if(matrix[j][i]==0)col=0; if(col==0)matrix[0][i]=0; } if(fircol==0)matrix[0][0]=0; for(int c=1;c<n;++c)//根据第一行处理每一列,第一列除外 if(matrix[0][c]==0){ for(int r=0;r<m;++r)matrix[r][c]=0; } for(int r=1;r<m;++r)//根据第一列处理每一行,第一行除外 if(matrix[r][0]==0){ for(int c=0;c<n;++c)matrix[r][c]=0; } if(firow==0) for(int c=0;c<n;++c)matrix[0][c]=0; if(fircol==0) for(int r=0;r<m;++r)matrix[r][0]=0; }};
- 105. Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- IntelliJ IDEA 的 20 个代码自动完成的特性
- Numeric Validation
- HDU 1689 Just a Hook (线段树)
- 剑指offer(12)-反转链表
- 电商之梳理相关Zookeeper相关知识---HA
- 105. Set Matrix Zeroes
- 电商之梳理Router相关知识---路由
- android动画使用三
- POJ 1236 Network of Schools【强连通Kosaraju+缩点+思维】
- AngularJs directive-transclude
- Web第一部分(1-2) 未写
- 链表高级算法--1
- 解决Oracle 11g在用EXP导出时,空表不能导出
- python 两个list 求交集,并集,差集