LeetCode JavaScript解答(3)未完全解决

今天还和上一篇一样,直接上题目。

题目

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two
positive integers r and c representing the row number and column
number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the
original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and
legal, output the new reshaped matrix; Otherwise, output the original
matrix.

Example 1:
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.

题目的意思大致是指给我们一个如n*m列矩阵,再给我们两个数r,c,让我们将其变换成一个r*c的矩阵,按行序遍历之后结构和原矩阵遍历结果相同。

题目分析

题目不难,首先要注意的是变换,也就是说最终得到的矩阵和原先矩阵的行列之积应该是相等的,如果不等,直接返回原矩阵即可;若相等,就使用for循环一个个写入就行了

算法

这里就直接贴discuss里面的高票回答了,Java的,很容易看懂

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;
}

代码

我自己根据上面的解法用js写的如下,可是不知道为什么报错,唉,js还是没仔细学好,在网上找了半天也没个头绪,今天先贴在这里,弄明白了再回来好好改一下

/**
 * @param {number[][]} nums
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
var matrixReshape = function(nums, r, c) {
    var n = nums.length;
    var m = nums[0].length;
    if(r*c !== n*m)
        return nums;
    var res = new Array(r);
    for(var i=0;i<r;i++){
        res[i]=new Array(c);
    }
    for(var j=0;j<r*c;j++){
        res[j/c][j%c]=nums[j/m][j%m];
    }
    return res;
};

顺带这里再贴一下其他人的js另一种解决方法
引自LeetCode discussion

var matrixReshape = function(nums, r, c) {
    if(nums[0].length * nums.length !== r*c){
        return nums;
    }

    var order = nums.reduce(function(acc,item){
        return acc.concat(item);
    }, [])

    var newMatrix =[];    
    order.reduce(function(accumulator, value, idx){
        if(idx === c-1 || (idx+1) % c === 0){
            accumulator.push(value);
            newMatrix.push(accumulator);
            accumulator = [];
        } else {
            accumulator.push(value);
        }
        return accumulator;
    },[]);

    return newMatrix;
};

就这样吧,还是滚去继续学习了

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值