标签:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
1)O(m+n)算法:
用两个数组,长度分别为m,n,如果有一个matrix[i][j] == 0,那么将数组col[j] = row[i] = 0;
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int>>& matrix) { 4 5 int rowsize = matrix.size(); 6 int colsize = matrix[0].size(); 7 if(rowsize == 0) return; 8 if(colsize == 0) return; 9 10 bool* row = new bool[rowsize]; 11 memset(row,false,rowsize); 12 bool* col = new bool[colsize]; 13 memset(col,false,colsize); 14 15 for(int i = 0 ; i < rowsize ;++i) 16 { 17 for(int j = 0 ;j < colsize;++j) 18 { 19 if(matrix[i][j] == 0) 20 { 21 row[i] = true; 22 col[j] = true; 23 } 24 } 25 } 26 for(int i = 0; i < rowsize; ++i) 27 { 28 if(row[i]){ 29 for(int j = 0; j < colsize; ++j) 30 matrix[i][j] = 0; 31 } 32 } 33 for(int j = 0; j < colsize; ++j) 34 { 35 if(col[j]){ 36 for(int i = 0; i < rowsize; ++i) 37 matrix[i][j] = 0; 38 } 39 } 40 } 41 };‘
2)O(1)算法:使用第一行第一列作为记录,一旦有matrix[i][j] == 0,就将max[0][j] = max[i][0] = 0;最后统一将所有的元素赋值
1 class Solution { 2 public: 3 void setZeroes(vector<vector<int>>& matrix) { 4 5 bool firstrow = false; 6 bool firstcol = false; 7 int rowsize = matrix.size(); 8 int colsize = matrix[0].size(); 9 if(rowsize == 0) return; 10 if(colsize == 0) return; 11 12 for(int j = 0;j < colsize; ++j) 13 { 14 if(!matrix[0][j]) 15 firstrow = true; 16 17 } 18 19 for(int i = 0;i < rowsize; ++i) 20 { 21 if(!matrix[i][0]) 22 firstcol = true; 23 24 } 25 for(int i=0;i < rowsize;++i) 26 { 27 for(int j = 0;j < colsize;++j) 28 29 { 30 if(!matrix[i][j]) 31 { 32 matrix[i][0] = matrix[0][j] = 0; 33 } 34 } 35 } 36 37 for(int j = 1;j < colsize; ++j) 38 { 39 if(!matrix[0][j]) 40 { 41 for(int i = 0;i < rowsize; ++i) 42 matrix[i][j] = 0; 43 } 44 } 45 for(int i = 1;i < rowsize; ++i) 46 { 47 if(!matrix[i][0]) 48 { 49 for(int j = 0;j < colsize; ++j) 50 matrix[i][j] = 0; 51 } 52 } 53 54 if(firstrow) 55 { 56 for(int j =0; j < colsize;++j) 57 { 58 matrix[0][j] = 0; 59 } 60 } 61 if(firstcol) 62 { 63 for(int i =0; i < rowsize;++i) 64 { 65 matrix[i][0] = 0; 66 } 67 } 68 } 69 };
标签:
原文地址:http://www.cnblogs.com/chdxiaoming/p/4719047.html