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;
          }
     }
}
相关文章
相关标签/搜索