【力扣100】73.矩阵置零

添加链接描述

python 复制代码
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        # 思路是1.记录每一个0元素的行和列下标 2.遍历全数组
        row_index=[]
        column_index=[]
        m=len(matrix)
        n=len(matrix[0])
        # print(m,n)
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==0:
                    row_index.append(i)
                    column_index.append(j)
        for i in range(m):
            for j in range(n):
                if(i in row_index or j in column_index):
                    matrix[i][j]=0

思路:

  1. 先扫一遍记录0
  2. 再扫一遍置0
  3. 时间复杂度就n*m太慢
  4. 空间复杂度是m+n


python 复制代码
class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        row = len(matrix)
        col = len(matrix[0])
        row0_flag = False
        col0_flag = False
        # 找第一行是否有0
        for j in range(col):
            if matrix[0][j] == 0:
                row0_flag = True
                break
        # 第一列是否有0
        for i in range(row):
            if matrix[i][0] == 0:
                col0_flag = True
                break

        # 把第一行或者第一列作为 标志位
        for i in range(1, row):
            for j in range(1, col):
                if matrix[i][j] == 0:
                    matrix[i][0] = matrix[0][j] = 0
        #print(matrix)
        # 置0
        for i in range(1, row):
            for j in range(1, col):
                if matrix[i][0] == 0 or matrix[0][j] == 0:
                    matrix[i][j] = 0

        if row0_flag:
            for j in range(col):
                matrix[0][j] = 0
        if col0_flag:
            for i in range(row):
                matrix[i][0] = 0

思路:

  1. 先记录第一行第一列有无0
  2. 把第一行第一列作为标志位
  3. 空间变成o(1)
  4. 时间还是o(n*m)
相关推荐
Swift社区1 天前
LeetCode 378 - 有序矩阵中第 K 小的元素
算法·leetcode·矩阵
墨染点香1 天前
LeetCode 刷题【73. 矩阵置零】
算法·leetcode·矩阵
林木辛1 天前
LeetCode热题 438.找到字符中所有字母异位词 (滑动窗口)
算法·leetcode
dragoooon341 天前
[优选算法专题二——NO.16最小覆盖子串]
c++·算法·leetcode·学习方法
1白天的黑夜11 天前
栈-1047.删除字符串中的所有相邻重复项-力扣(LeetCode)
c++·leetcode·
im_AMBER1 天前
Leetcode 18 java
java·算法·leetcode
愚润求学1 天前
【贪心算法】day9
c++·算法·leetcode·贪心算法
songx_991 天前
leetcode29( 有效的括号)
java·数据结构·算法·leetcode
东方芷兰1 天前
Leetcode 刷题记录 21 —— 技巧
java·算法·leetcode·职场和发展·github·idea