LeetCode 73. Set Matrix Zeroes

题目:

给定一个mxn矩阵,如果一个元素是0,把它的行和列都设为0(就在矩阵上进行修改)

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

跟进:

空间复杂度:O(m×n) → O(m+n) → O(1)

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

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?

思路:

分别用矩阵的第一行和第一列保存该列/行是否需要清零

即,用第一行的第i个数,保存第i列是否需要清零;用第一列的第j个数,保存第j行是否需要清零

特别的:用两个常数分别表示第一行和第一列是否需要清零(否则会出现错误)

代码步骤:

先遍历矩阵,进行标记;

根据标记清零第m行~1行

根据标记清零第n列~1列

根据flag标记清零第0行

根据flag标记清零第0列

 

代码:

class Solution {
    public void setZeroes(int[][] matrix) {
        int row0flag = 0;
        int col0flag = 0;
    	
        for(int i=0;i0;i--) {
            if(matrix[i][0]==0) {
                setRow(matrix, i);
            }
        }

        for(int i=matrix[0].length-1;i>0;i--) {
            if(matrix[0][i]==0) {
                setCol(matrix, i);
            }
        }

        if(row0flag==1) {
            for(int i=0;i

 

你可能感兴趣的:(LeetCode)