ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 0073 Set Matrix Zeroes

2022-04-25 07:00:41  阅读:185  来源: 互联网

标签:Zeroes Set matrix int cols col0 states 标识 0073


原题传送门

1. 题目描述

2. Solution

1、思路分析
第1阶段: 逐个元素遍历,如果matrix[i][j]等于0,就把行首元素matrix[i][0],列首元素matrix[0][j]置为0。
第2阶段: 从后往前遍历,若行首为0,则把当前行均置为0;若列首为0,则把当前列均置为0。
注意: 因为第1行与第1列的元素使用了同一个位置 [0][0] 来标识其中是否含有0,产生了二义性,所以必须分开。这样,使用col0变量来标识 第1列中是否含有0。

2、代码实现

package Q0099.Q0073SetMatrixZeroes;

public class Solution {
    /*
      My idea is simple:
      store states of each row in the first of that row, and store states of each column in the first of that column.
      Because the state of row0 and the state of column0 would occupy the same cell, I let it be the state of row0,
      and use another variable "col0" for column0.
      因为第1行与第1列的元素使用了同一个位置 [0][0] 来标识其中是否含有0,产生了二义性,所以必须分开。这样,使用col0变量来标识 第1列中是否含
      有0。
      In the first phase, use matrix elements to set states in a top-down way.
      In the second phase, use states to set matrix elements in a bottom-up way.
     */
    public void setZeroes(int[][] matrix) {
        int col0 = 1, rows = matrix.length, cols = matrix[0].length;

        for (int i = 0; i < rows; i++) {
            if (matrix[i][0] == 0) col0 = 0;
            for (int j = 1; j < cols; j++)
                if (matrix[i][j] == 0)
                    matrix[i][0] = matrix[0][j] = 0;
        }

        for (int i = rows - 1; i >= 0; i--) {
            for (int j = cols - 1; j >= 1; j--)
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            if (col0 == 0) matrix[i][0] = 0;
        }
    }
}

3、复杂度分析
时间复杂度: O(m * n)
空间复杂度: O(1)

标签:Zeroes,Set,matrix,int,cols,col0,states,标识,0073
来源: https://www.cnblogs.com/junstat/p/16188580.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有