leetcode 566. Reshape the Matrix
来源:互联网 发布:爱易编程工具箱 编辑:程序博客网 时间:2024/06/13 03:52
1.题目
Reshape the Matrix
例1:
Input:
nums = [[1,2], [3,4]]r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
元素横向展开,2*2的矩阵转为1*4的矩阵
例 2:
Input:
nums = [[1,2], [3,4]]r = 2, c = 4
Output:
[[1,2], [3,4]]
Explanation:
2*2的矩阵无法转为2*4的矩阵,所以输出原矩阵。
2.解法
(1)origin_r * origin_c 的矩阵 reshape为 r*c的矩阵,需要满足:
origin_r * origin_c=r*c
(2)元素位置对应的关系
如果将矩阵横向展开为一维数组,元素个数为n=origin_r * origin_c
在元素在一维数组中对应的位置i:
原矩阵位置[i/origin_c,i%origin_c]
新矩阵位置[i/c,i%c]
3.代码
c++
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { //原矩阵的行,列 int origin_r = nums.size(); int origin_c = nums[0].size(); int n = origin_c*origin_r;//元素个数 if (n == r*c) { //新矩阵 vector<vector<int>> newMaxtrix(r, vector<int>(c, 0)); for (int i = 0; i < n; i++) newMaxtrix[i / c][i%c] = nums[i / origin_c][i%origin_c]; return newMaxtrix; } else return nums; }
python
def matrixReshape(self, nums, r, c): origin_r=len(nums)#行 origin_c=len(nums[0])#列 if origin_c*origin_r==r*c:#可以reshape temp=[num for row in nums for num in row]#展开成一维数组 newMatrix=[[0 for j in xrange(c)] for i in xrange(r)] for i in xrange(r): for j in xrange(c): newMatrix[i][j]=temp[i*c+j] return newMatrix else:#无法reshape return nums
2 0
- leetcode 566. Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- [leetcode]566. Reshape the Matrix
- LeetCode:566. Reshape the Matrix
- leetcode 566. Reshape the Matrix
- LeetCode | 566. Reshape the Matrix
- leetcode-566. Reshape the Matrix
- LeetCode 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- LeetCode-566. Reshape the Matrix
- LeetCode * 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- leetcode.566.Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode] 566. Reshape the Matrix
- 【LeetCode】566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- 机器学习路线图(附资料)
- hive环境---安装系列五
- 【POJ2187】Beauty Contest-凸包+旋转卡壳
- python_movie_apriori
- java中的静态属性初始化--static块
- leetcode 566. Reshape the Matrix
- css3之pointer-events
- Contest Strategy
- 最大子矩阵 题解
- 如何解决ubutun中vi编辑器里面的显示行号,以及tab键占4位
- java集合常见问题
- Python机器学习库SKLearn的特征选择
- C语言编程练习——从一个字符数组中读出相应的整数、实数
- react native PixelRatio获取像素密度