栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【leetcode】566. 重塑矩阵(python)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【leetcode】566. 重塑矩阵(python)

思路:

先展成一维数组,再映射成 r 行 c 列 数组

写法一:
class Solution(object):
    def matrixReshape(self, mat, r, c):
        """
        :type mat: List[List[int]]
        :type r: int
        :type c: int
        :rtype: List[List[int]]
        """
        if not mat:
            return []
        row_mat = len(mat)
        col_mat = len(mat[0])
        res = []
        all_num = []    # note : res = all_num = []  # error !  这样写会占用同一块存储空间
        if row_mat * col_mat == r * c:
            for i in range(row_mat):
                for j in range(col_mat):
                    all_num.append(mat[i][j])   # 展成一维数组,即 flatten操作
            tmp = []
            for k in range(row_mat * col_mat):
                tmp.append(all_num[k])
                if (k + 1) % c == 0:
                    res.append(tmp)
                    tmp = []
        else:
            return mat
        return res
写法二:(简洁版)
class Solution(object):
    def matrixReshape(self, mat, r, c):
        m, n = len(mat), len(mat[0])
        if m * n != r * c:
            return mat
        ans = [[0] * c for _ in range(r)]
        for x in range(m * n):
            ans[x // c][x % c] = mat[x // n][x % n]
        return ans
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829206.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号