1. 程式人生 > >[Leetcode] set matrix zeroes 矩陣置零

[Leetcode] set matrix zeroes 矩陣置零

div const amp 列數 clas size cto target 參考

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(m n) 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. 思路:因為,數組中值為0的元素可能不止一個,所以,常規的思路是,遍歷數組,記下值為0元素的行、列數,然後根據其所在的記下的行、列將對應行所在的值全賦值為0,但這樣會需要O(m+n)的額外空間。所以換一種思路,我們可以遍歷數組,若遇到值為0,則將其對應的第一行、第一列的值賦為0,最後根據第一行、第一列的值,更新數組。這樣做存在一個問題,那就是,若第一行、第一列中原本就存在0,此時需要更新數組時,如何區分?我們可以先確定第一行、第一列是否存在0,然後,更新完剩下的數組以後,根據是否存在0,決定第一行、第一列的是否全部更新為0。代碼如下:
 1 class
Solution { 2 public: 3 void setZeroes(vector<vector<int> > &matrix) 4 { 5 int row=matrix.size(); 6 int col=matrix[0].size(); 7 8 if(row==0||col==0) return; 9 10 bool rFlag=false,cFlag=false; 11 for(int i=0;i<row;++i) 12 {
13 if(matrix[i][0]==0) 14 { 15 rFlag=true; 16 break; 17 } 18 } 19 for(int i=0;i<col;++i) 20 { 21 if(matrix[0][i]==0) 22 { 23 cFlag=true; 24 break; 25 } 26 } 27 28 for(int i=1;i<row;++i) 29 { 30 for(int j=1;j<col;++j) 31 { 32 if(matrix[i][j]==0) 33 { 34 matrix[i][0]=0; 35 matrix[0][j]=0; 36 } 37 } 38 } 39 40 for(int i=1;i<row;++i) 41 { 42 for(int j=1;j<col;++j) 43 { 44 if(matrix[i][0]==0||matrix[0][j]==0) 45 matrix[i][j]=0; 46 } 47 } 48 49 if(rFlag) 50 { 51 for(int i=0;i<row;++i) 52 matrix[i][0]=0; 53 } 54 if(cFlag) 55 { 56 for(int i=0;i<col;++i) 57 matrix[0][i]=0; 58 } 59 60 } 61 };

代碼參考了Gradyang的博客

[Leetcode] set matrix zeroes 矩陣置零