【力扣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)
相关推荐
TimberWill7 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit7 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung7 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
LYFlied11 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
sin_hielo12 小时前
leetcode 3074
数据结构·算法·leetcode
程序员-King.12 小时前
day124—二分查找—最小化数组中的最大值(LeetCode-2439)
算法·leetcode·二分查找
im_AMBER14 小时前
Leetcode 85 【滑动窗口(不定长)】最多 K 个重复元素的最长子数组
c++·笔记·学习·算法·leetcode·哈希算法
2401_8414956415 小时前
【LeetCode刷题】跳跃游戏Ⅱ
数据结构·python·算法·leetcode·数组·贪心策略·跳跃游戏
rannn_11116 小时前
【SQL题解】力扣高频 SQL 50题|DAY5
数据库·后端·sql·leetcode·题解
LYFlied17 小时前
【每日算法】LeetCode 279. 完全平方数(动态规划)
前端·算法·leetcode·面试·动态规划