python矩阵reshape_[LeetCode Python3]566. Reshape the Matrix(重塑矩阵)
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例 1:
输入:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
输出:
[[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
示例 2:
输入:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
输出:
[[1,2],
[3,4]]
解释:
没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
注意:
给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。
思路:重塑矩阵前后元素个数相同,下面是Python解题代码。
class Solution:
def matrixReshape(self, nums, r, c):
"""
:type nums: List[List[int]]
:type r: int
:type c: int
:rtype: List[List[int]]
"""
rr = len(nums)
cc = len(nums[0])
retl = []
if rr * cc < r * c:
return nums
else:
t = []
for i in range(rr):
for j in range(cc):
t.append(nums[i][j])
m = 0
for i in range(r):
retl.append(t[m:m + c])
m += c
return retl
python矩阵reshape_[LeetCode Python3]566. Reshape the Matrix(重塑矩阵)相关推荐
- leetcode讲解--566. Reshape the Matrix
题目 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ne ...
- Leetcode PHP题解--D53 566. Reshape the Matrix
2019独角兽企业重金招聘Python工程师标准>>> D53 566. Reshape the Matrix 题目链接 566. Reshape the Matrix 题目分析 给 ...
- LeetCode 566 Reshape the Matrix 解题报告
题目要求 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ...
- LeetCode 566. Reshape the Matrix
题目: In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a n ...
- leetcode 566. Reshape the Matrix | 566. 重塑矩阵(Java)
题目 https://leetcode.com/problems/reshape-the-matrix/ 题解 考矩阵变换,简单题,不多说,直接上代码. class Solution {public ...
- leetCode题解之Reshape the Matrix
1.题目描述 2.分析 使用了一个队列. 3.代码 1 vector<vector<int>> matrixReshape(vector<vector<int> ...
- python3中zip函数_用python实现矩阵转置,python3 中zip()函数
前几天群里有同学提出了一个问题:手头现在有个列表,列表里面两个元素,比如[1, 2],之后不断的添加新的列表,往原来相应位置添加.例如添加[3, 4]使原列表扩充为[[1, 3], [2, 4]],再 ...
- Leetcode刷题100天—566. 重塑矩阵(数组)—day25
前言: 作者:神的孩子在歌唱 大家好,我叫运智 566. 重塑矩阵 难度简单233收藏分享切换为英文接收动态反馈 在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n ...
- LeetCode 74. Search a 2D Matrix--有序矩阵查找--python,java,c++解法
题目地址:Search a 2D Matrix - LeetCode Write an efficient algorithm that searches for a value in an m x ...
最新文章
- 摩卡业务服务管理(Mocha BSM)解决方案
- Linux 修改 IP地址 和 网关
- 转:C# Interview Questions
- php 递归函数自调用函数,PHP闭包实现函数的自调用实现递归
- C++内存管理(1)
- 这算抄百度?Google为信息流告别简洁搜索框,也押注短视频
- android 制作 win10,你真没有看错!Android手机一秒变Win10
- w ndoWs8pE模式下载,电脑店超级U盘启动盘制作工具V6.8(全能版)
- 新手建站推广完美教程(重点推荐)
- uniapp更改switch大小
- C语言 数据结构 栈的线性实现 基本操作代码
- windows(微软知识库)可以根据事件ID查看 各种事件
- 透过爷爷的一生,浅析选择的重要性
- 软文营销推广抓住写作风格让文案不再平庸
- word文档图标变成白纸_Word图标变成白框加WORD图标的解决方案
- 一.JavaWeb学习路线
- 城市与地区级联选择框的使用
- LSTM的loss和accuracy近乎不变问题
- 潘粤明版《鬼吹灯》口碑炸裂!豆瓣8.3高分到底好看在哪?
- 计算机基础知识(2)