1. 程式人生 > >LeetCode刷題Medium篇 Set Matrix Zeroes

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;
            }
        }
    }
}