【力扣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)
相关推荐
2351623 分钟前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
tkevinjd4 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤5 小时前
【leetcode刷题007】leetcode116、117
算法·leetcode
Swift社区8 小时前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato8 小时前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167
巴里巴气9 小时前
第15题 三数之和
数据结构·算法·leetcode
西阳未落10 小时前
LeetCode——双指针(进阶)
c++·算法·leetcode
熬了夜的程序员11 小时前
【LeetCode】69. x 的平方根
开发语言·算法·leetcode·职场和发展·动态规划
Swift社区20 小时前
LeetCode 394. 字符串解码(Decode String)
算法·leetcode·职场和发展
tt55555555555521 小时前
LeetCode进阶算法题解详解
算法·leetcode·职场和发展