zoukankan      html  css  js  c++  java
  • leetcode-mid-array-73 set matrix zeros

    mycode

    空间复杂度 m+n

    思路:用set把为0元素所在行、列记录下来

    注意:注释的方法更快

    class Solution(object):
        def setZeroes(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: None Do not return anything, modify matrix in-place instead.
            """
            rows = set()
            cols = set()
            count_row = len(matrix)
            count_col = len(matrix[0])
            for i in range(count_row):
                for j in range(count_col):
                    if matrix[i][j] == 0:
                        rows.add(i)
                        cols.add(j)
            #for row in rows:
            #    matrix[row] = [0]*count_col
            #for col in cols:
            #    for line in matrix:
            #        line[col] = 0
            for i in rows:
                for j in xrange(count_col):
                    matrix[i][j] = 0
            for i in xrange(count_row):
                for j in cols:
                    matrix[i][j] = 0
            return matrix

    参考:

    常数空间,用第一行第一列来记录

    class Solution(object):
        def setZeroes(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: None Do not return anything, modify matrix in-place instead.
            """
            first_row = False
            first_col = False
            m = len(matrix)
            n = len(matrix[0]) #[[]]
            if m == 0 or n == 0 : 
                return
            flag = -1
            for i in range(m):
                if matrix[i][0] == 0: #说明第一列本来最后就应该都等于0,以免被覆盖
                    first_col = True
            for j in range(n):
                if matrix[0][j] == 0: 
                    first_row = True
            for i in range(1,m):
                for j in range(1,n):
                    if matrix[i][j] == 0:
                        matrix[i][0] = matrix[0][j] = 0
            #第一行所有列,第一列所有行 为对照表,所以节省了空间
            for i in range(1,m):
                for j in range(1,n):
                    if matrix[0][j] == 0 or matrix[i][0] == 0:
                        matrix[i][j] = 0 
            if first_row:
                for j in range(n):
                    matrix[0][j] = 0
            if first_col:
                for i in range(m):
                    matrix[i][0] = 0
  • 相关阅读:
    docker 知识汇总1-镜像管理
    合并两个git repository
    这一次, 信报箱震惊世界
    python实现括号分组
    linux case菜单代码示例
    oracle 11gR2 client安装(Red Hat Enterprise Linux Server release 5.5 (Tikanga) 安装ORACLE客户端)
    SYSAUX表空间过大处理
    SYSAUX表空间大于33G问题处理
    window 给链接加下划线或取消下划线
    ORACLE11G_win32监听程序不支持服务
  • 原文地址:https://www.cnblogs.com/rosyYY/p/10963786.html
Copyright © 2011-2022 走看看