Set Matrix zeroes--LeetCode

来源:互联网 发布:java web报表插件 编辑:程序博客网 时间:2024/06/17 20:58

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

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?

思路:这里只是提到了空间复杂度,如果使用O(m + n)的空间复杂度,那么可以遍历这个数组,申请两个hash表,一个表示行,一个表示列,遍历数组分别赋值,然后再次遍历数组,根据hash表中表示看是否需要将此位置标记为0.

如果想使用常量空间,不知道使用bitmap作为hash表是否达到要求,如果没有达到,可以使用二维数组本身的第一行和第一列来表示上面申请的两个hash表。

void setZeroes(vector<vector<int> > &matrix) {          bool firstLine = false;          bool firstRow = false;          for(int i=0;i<matrix[0].size();i++)          {              if(matrix[0][i] == 0){                  firstLine = true;                  break;              }          }                    for(int i=0;i<matrix.size();i++)          {              if(matrix[i][0] == 0){                  firstRow = true;                  break;              }          }                    for(int i=1;i<matrix.size();i++)          {              for(int j=1;j<matrix[0].size();j++)              {                  if(matrix[i][j] == 0)                  {                      matrix[i][0] = 0;                      matrix[0][j] = 0;                  }              }          }                    for(int i=1;i<matrix.size();i++)          {              for(int j=1;j<matrix[0].size();j++)              {                  if(matrix[i][0] == 0 || matrix[0][j] == 0)                  {                      matrix[i][j]=0;                  }              }          }                    if(firstLine){              for(int i=0;i<matrix[0].size();i++)              {                  matrix[0][i] = 0;              }          }                    if(firstRow){              for(int i=0;i<matrix.size();i++)              {                  matrix[i][0] = 0;              }          }      }  


0 0
原创粉丝点击