【力扣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)
相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
元亓亓亓3 天前
LeetCode热题100--105. 从前序与中序遍历序列构造二叉树--中等
算法·leetcode·职场和发展
仙俊红3 天前
LeetCode每日一题,20250914
算法·leetcode·职场和发展
_不会dp不改名_3 天前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌3 天前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
爱编程的化学家3 天前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
吃着火锅x唱着歌3 天前
LeetCode 1446.连续字符
算法·leetcode·职场和发展
愚润求学3 天前
【贪心算法】day10
c++·算法·leetcode·贪心算法