LeetCode算法系列:73. Set Matrix Zeroes

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82777499

题目描述:

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

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

Follow up:

  • 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?

算法实现

题目中的要求主要是要求我们减小使用多余的空间,建立一个大小为m的数组和一个大小为n的数组分别记录每行每列是否有零元素,需要的空间是O(m + n),如果我们使用给定的matrix的第一行和第一列记录它的其余行和列的是否有零元素的情况,当然首先要先用两个bool型量记录其第一行和第一列的情况,我们就可以在常数空间内完成要求

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        if(matrix.empty())return ;
        int m = matrix.size();
        int n = matrix[0].size();
        bool row1 = false, Col1 = false;
        for(int i = 0; i < n; i ++)
            if(matrix[0][i] == 0){
                row1 = true;
                break;
            }
        for(int i = 0; i < m; i ++)
            if(matrix[i][0] == 0){
                Col1 = true;
                break;
            }

        for(int i = 0; i < m; i ++)
            for(int j = 0; j < n; j ++)
                if(matrix[i][j] == 0)matrix[i][0] = 0, matrix[0][j] = 0;

            
        for(int i = 1; i < m; i ++)
            if(matrix[i][0] == 0)
                for(int j = 1; j < n; j ++)
                    matrix[i][j] = 0;                
        for(int j = 1; j < n; j ++)
            if(matrix[0][j] == 0)
                for(int i = 1; i < m; i ++)
                    matrix[i][j] = 0;
                
        if(row1)
            for(int i = 0; i < n; i ++)
                matrix[0][i] = 0;
        if(Col1)
            for(int i = 0; i < m; i ++)
                matrix[i][0] = 0;
        return ;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82777499