多维数组“重塑”

在MATLAB中,有一个非常有用的功能称为“重塑”,可以重塑一个矩阵与不同大小的一个新的但保持其原始数据。

给你一个矩阵表示为一个二维数组,和两个正整数r和c代表希望重塑的行数和列数矩阵,分别。

重塑矩阵需要充满原始矩阵的所有元素在同一个row-traversing顺序。

如果给出的“重塑”操作参数是可能的,合法的,输出新的重塑矩阵;否则,输出原始矩阵。

Example1

Input: 
nums = 
[[1,2],
 [3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

Example2

Input: 
nums = 
[[1,2],
 [3,4]]
r = 2, c = 4
Output: 
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.


解决
public int[][] matrixReshape(int[][] nums, int r, int c) {
    int n = nums.length, m = nums[0].length;
    if (r*c != n*m) return nums;
    int[][] res = new int[r][c];
    for (int i=0;i<r*c;i++) 
        res[i/c][i%c] = nums[i/m][i%m];
    return res;
}


res[i/c][i%c]=nums[i/m][i%m];

或者可以先创建一个Queue,把数组元素先   存放进去,后用Queue.remove()方法(删除并返回队头元素)。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值