NOWCODER 剑指offer 顺时针打印矩阵

折腾了好久。。写得好繁琐。。相当于试出来的

运行时间:27ms

占用内存:5852k

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        if not matrix:
            return []
        m = len(matrix)
        n = len(matrix[0])
        if m==1:
            return matrix[0]
        if n==1:
            return [b[0] for b in matrix]
        i = m//2
        j = n//2
        result = []
        cnt = 1
        while (i and j):
            if(i):
                #第cnt个循环的行正向
                result += matrix[cnt-1][cnt-1:(n-1)-cnt +1]
                if j:
                    #第cnt个循环的列正向
                    result += [b[(n-1)-(cnt-1)] for b in matrix[cnt-1:(m-1)-cnt +1]]
                #第cnt个循环的行负向
                result += matrix[(m-1)-(cnt-1)][(n-1)-(cnt-1):cnt-1:-1]
                if j:
                    #第cnt个循环的列负向
                    result += [b[cnt-1] for b in matrix[(m-1)-(cnt-1):cnt-1:-1]]
            i -= 1
            j -= 1
            cnt += 1
        #列为奇,且列小于等于行,再加一列
        if n%2 and (not j):
            result += [b[(n-1)-(cnt-1)] for b in matrix[cnt-1:(m-1)-cnt +1+1]]
            return result
        #行为奇,且行小于列
        if m%2 and (not i):
            result += matrix[cnt-1][cnt-1:(n-1)-cnt +1+1]
            return result
        return result

————————————————————————————————————————————

学会利用pop(),不管是一维,二维,还是在循环里,都有效

第一种,每次取第一列,然后旋转矩阵

运行时间:22ms

占用内存:5732k

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        def turn(mat):
            if (not mat) or (not mat[0]):
                return None
            #m = len(mat)
            n = len(mat[0])
            result = []
            for i in range(n):
                result.append([a[n-i-1] for a in mat[:]])
            return result

        res = []
        while (matrix and matrix[0]):
            res += matrix.pop(0)
            matrix = turn(matrix)
        return res

____________________________________________________

另一种更简洁的pop方法,不用每次旋转矩阵,只需要列也pop掉即可

运行时间:31ms

占用内存:5624k

# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        res = []
        while(matrix):
            res += matrix.pop(0)
            if(matrix and matrix[0]):
                for row in matrix:
                    res.append(row.pop())
            if matrix:
                res += matrix.pop()[::-1]
            if matrix and matrix[0]:
                for row in matrix[::-1]:
                    res.append(row.pop(0))
        return res

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值