码迷,mamicode.com
首页 > 其他好文 > 详细

p99 矩阵置零(leetcode 73)

时间:2020-04-07 18:34:34      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:span   示例   length   color   数组   java   amp   solution   boolean   

一:解题思路

一种比较容易想到的解法是定义2个记录行和列的数组,先遍历一遍原始的数组,如果出现了0,这记录到行列数组为true。然后再遍历一遍数组,如果在行列数组中标记为true了,则将所在的行列全部置0.这种方法用了2个额外的数组,空间复杂度不够低。另外一种方法可以将空间复杂度变为O(1)。Time:O(n^2),Space:O(1)

二:完整代码示例 (C++版和Java版)

C++:

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) 
    {
        int m = matrix.size(), n = matrix[0].size();
        bool col0 = false, row0 = false;

        for (int i = 0; i < m; i++)
            if (matrix[i][0] == 0) col0 = true;
        for (int j = 0; j < n; j++)
            if (matrix[0][j] == 0) row0 = true;

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (matrix[i][j] == 0)
                    matrix[i][0] = matrix[0][j] = 0;

        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;

        if (col0)
            for (int i = 0; i < m; i++)
                matrix[i][0] = 0;
        if (row0)
            for (int j = 0; j < n; j++)
                matrix[0][j] = 0;
    }
};

Java:

class Solution {
        public void setZeroes(int[][] matrix)
        {
               int m=matrix.length,n=matrix[0].length;
               boolean row0=false,col0=false;

               for(int i=0;i<m;i++)
                   if(matrix[i][0]==0)
                       col0=true;
               for(int j=0;j<n;j++)
                   if(matrix[0][j]==0)
                       row0=true;
               for(int i=1;i<m;i++)
                   for(int j=1;j<n;j++)
                       if(matrix[i][j]==0)
                       {
                           matrix[i][0]=0;
                           matrix[0][j]=0;
                       }

               for(int i=1;i<m;i++)
                   for(int j=1;j<n;j++)
                       if(matrix[i][0]==0 || matrix[0][j]==0)
                           matrix[i][j]=0;
               if(col0)
                   for(int i=0;i<m;i++)
                       matrix[i][0]=0;
               if(row0)
                   for(int j=0;j<n;j++)
                       matrix[0][j]=0;
        }
    }

 

p99 矩阵置零(leetcode 73)

标签:span   示例   length   color   数组   java   amp   solution   boolean   

原文地址:https://www.cnblogs.com/repinkply/p/12654759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!