【力扣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)
相关推荐
小欣加油8 小时前
leetcode56 合并区间
c++·算法·leetcode·职场和发展
8Qi811 小时前
LeetCode 516:最长回文子序列
算法·leetcode·职场和发展·动态规划
小欣加油16 小时前
leetcode287寻找重复数
数据结构·c++·算法·leetcode
怪兽学LLM17 小时前
LeetCode 438 找到字符串中所有字母异位词(Python 固定滑动窗口+字符计数解法)
python·算法·leetcode
Tisfy17 小时前
LeetCode 3689.最大子数组总值 I:What The Medium
算法·leetcode·题解·贪心·模拟·脑筋急转弯
moeyui70518 小时前
LeetCode 380:Insert Delete GetRandom O(1) 题解和一些延伸
算法·leetcode·职场和发展
圣保罗的大教堂18 小时前
leetcode 3689. 最大子数组总值 I 中等
leetcode
退休倒计时19 小时前
【每日一题】LeetCode 15. 三数之和 TypeScript
数据结构·算法·leetcode·typescript
小欣加油19 小时前
leetcode3689最大子数组总值I
c++·算法·leetcode·职场和发展·贪心算法
人道领域20 小时前
【LeetCode刷题日记】90.子集Ⅱ--- 归纳题解
java·开发语言·leetcode