Set Matrix Zeroes
来源:互联网 发布:法国 知乎 编辑:程序博客网 时间:2024/05/20 17:10
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
题目解析:
将一个矩阵中0所在行,以及所在列都置为0.
方法一:
将矩阵中,0的行和列的下标保存下来,并且分别去除里面重复的下标,之后遍历矩阵,将记录的这些行和列均置为0.代码如下:
class Solution {public: bool exit_col(vector<int> col_dex,int col) { vector<int>::iterator s=find(col_dex.begin(),col_dex.end(),col);//第一个参数是array的起始地址,第二个参数是array的结束地址 if( s !=col_dex.end())//找到 return true; return false; } void setZeroes(vector<vector<int>>& matrix) { if(matrix.size()==0) return; int m=matrix.size(); int n=matrix[0].size(); vector<int> col_dex; vector<int> row_dex; bool flag=0; for(int row=0;row<m;row++) { for(int col=0;col<n;col++) { if(matrix[row][col]==0) { if(!exit_col(col_dex,col)) col_dex.push_back(col); if(!exit_col(row_dex,row)) row_dex.push_back(row); } } } for(int i=0;i<row_dex.size();i++) { for(int j=0;j<n;j++) matrix[row_dex[i]][j]=0; } for(int i=0;i<col_dex.size();i++) { for(int j=0;j<m;j++) matrix[j][col_dex[i]]=0; } }};
方法二:
将有0出现的元素的所在行的第一个元素,和所在列的第一个元素置为0,因为当零出现时,这些都将置为0,是相同的,起先只将第一个元素置为0,起到了标记的作用。之后从右下方向上遍历矩阵,如果此元素所在行或者所在列的第一个元素为0,则将该元素置0.代码如下:class Solution {public: void setZeroes(vector<vector<int>>& matrix) { if(matrix.size()==0) return; int m=matrix.size(); int n=matrix[0].size(); int flag=1; for(int row=0;row<m;row++) { if(matrix[row][0]==0) flag=0; for(int col=1;col<n;col++) { if(matrix[row][col]==0) { matrix[row][0]=0; matrix[0][col]=0; } } } for(int row=m-1;row>=0;row--) { for(int col=n-1;col>=1;col--) { if(matrix[row][0]==0||matrix[0][col]==0) { matrix[row][col]=0; } } if(flag==0) matrix[row][0]=0; } }};
值得注意的是:在方法二中,列都是从第二个元素开始,到第二个元素截至,第一个元素特殊处理,这是为了防止第一行或者第一列的元素中本身就有0,造成的过多置0情况。如下:
1 1 2
0 1 2
如果不特殊处理将变成:
0 0 0
0 0 0
做特殊处理之后,只有matrix[row][0]=0;其他的matrix[row][j]不改变;如下:
0 1 2
0 0 0
0 0
- 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
- Set Matrix Zeroes
- [7] MQTT,mosquitto,Eclipse Paho---MQTT消息格式之CONNACK消息分析
- 2015061204 - jdbctemplate中的queryForIntf方法
- [安卓]手机管家(五)防盗之加密
- A simple Complex class
- 数据结构(三)---队列:
- Set Matrix Zeroes
- 6.12
- 如何阅读他人的程序代码
- 树莓派共享文件至pc(samba)
- LeetCode——Happy Number
- [leetcode] Binary Tree Inorder Traversal
- 2015061205 - 找工作相关问题
- java中对象句柄的解释
- 基于MINA框架快速开发网络应用程序