Set Matrix Zeroes

https://leetcode.com/problems/set-matrix-zeroes/markdown

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

Follow up:idea

Did you use extra space?spa

A straight forward solution using O(mn) space is probably a bad idea.code

A simple improvement uses O(m + n) space, but still not the best solution.element

Could you devise a constant space solution?leetcode

題意:n*m矩陣,若是有一個元素是0,則把該行和該列所有變爲0。要求時間複雜度爲O(mn),空間複雜度O(1)get

思路:遍歷n*m的矩陣,若是發現0則把該行和該列的第一個元素標記爲0,若是是第0行或第0列,則使用兩個變量標記是否存在0。遍歷完後從第一行和第一列開始,若是發現0行或0列中爲0的那些列和行所有置零,最後判斷以前的兩個變量,若是0行有零則全置零,若是0列有零則全置零。it

實現:io

public class Solution {
      public void setZeroes( int[][] matrix) {
           int i , j ;
           boolean c1 = false, r1 = false; // 用來標記零行或零列是否有零

           // 遍歷矩陣
           for (i = 0; i < matrix .length ; i ++) {
               for (j = 0; j < matrix [i ].length ; j ++) {
                    if (matrix [i ][j ] == 0) {
                         if (i == 0 && j == 0) { // 若是零行零列全有零則標記
                              r1 = c1 = true ;
                        } else if (i == 0 && j != 0) { // 若是i爲零則有零列的0號元素置零
                              r1 = true ;
                              matrix[0][ j ] = 0;
                        } else if (i != 0 && j == 0) { // 若是j爲零則有零行的0號元素置零
                              c1 = true ;
                              matrix[ i][0] = 0;
                        } else {// 都不爲零,則把該元素所在行和列的第0個元素都置零
                              matrix[0][ j ] = 0;
                              matrix[ i][0] = 0;
                        }
                   }
              }
          }
           // 根據0列對全部行處理
           for (i = 1; i < matrix .length ; i ++) {
               if (matrix [i ][0] == 0)
                    for (j = 1; j < matrix [i ].length ; j ++)
                         matrix[ i][ j ] = 0;
          }
           // 根據0行對全部列處理
           for (i = 1; i < matrix [0].length ; i ++) {
               if (matrix [0][i ] == 0)
                    for (j = 1; j < matrix .length ; j ++)
                         matrix[ j ][i ] = 0;
          }
           // 處理零行
           if (r1 ) {
               for (i = 0; i < matrix [0].length ; i ++)
                    matrix[0][ i] = 0;
          }
           // 處理零列
           if (c1 ) {
               for (i = 0; i < matrix .length ; i ++)
                    matrix[ i][0] = 0;
          }
     }
}
相關文章
相關標籤/搜索