LeetCode刷题Medium篇 Set Matrix Zeroes

题目

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?

十分钟思考

如何利用常量空间解决这个问题?首先扫描二维矩阵,如果发现是0,怎么操作把所在行,所在列都设置为0?看了思路剔除第一行,第一列,然后如果ij为0,则把行首,列首标记为0,表示整个行或者列都为0,在第二次循环都时候根据行首或者列首,任何一个为0,全部更新为0。最后处理第一行和第一列,第一行根据[0][0]判断,第一个列在第一次循环都时候设置flag表示是否需要全部设置为0,代码如下:

class Solution {
    public void setZeroes(int[][] matrix) {
        int row=matrix.length;
        int col=matrix[0].length;
        boolean isZeroCol=false;
        for(int i=0;i<row;i++){
             if(matrix[i][0]==0){
                    isZeroCol=true;
                }
            for(int j=1;j<col;j++){
                if(matrix[i][j]==0){
                    matrix[i][0]=0;
                    matrix[0][j]=0;
                }
                
            }
        }
        //标注完毕,更新元素
        for(int i=1;i<row;i++){
            for(int j=1;j<col;j++){
                if(matrix[i][0]==0||matrix[0][j]==0){
                    matrix[i][j]=0;
                }
            }
            
        }
        if(matrix[0][0]==0){
            for(int i=0;i<col;i++){
                matrix[0][i]=0;
            }
        }
        if(isZeroCol){
            for(int j=0;j<row;j++){
                matrix[j][0]=0;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85601720