566. Reshape the Matrix

Posted agentgamer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了566. Reshape the Matrix相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/reshape-the-matrix/description/

简单有趣,也稍微窥探了一下matlab 和numpy 里面reshape 的算法。当然现实要比这个题要复杂,比如numpy 里面reshape 可以只接受一个参数,然后自动推导出另一个参数。

具体的思路没有什么难度,主要考察细心?一是非法情况的判断,简单的就是行x列不相等的情况。然后就是怎么确保row traversing order 的问题,我通过一个简单的帮助函数来做。

class Solution {
public:
    //return the n-th element of m using row traversing
    int rowTraverse(vector<vector<int>>& m, int n) {
        for (vector<int>& row : m) {
            if (n < row.size()) {
                return row[n];
            }
            n -= row.size();
            continue;
        }
    }
    
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        //check the invalid cases
        //since its the matrix, we can assume that every row has the same amount of elements.
        int rows = nums.size();
        int cols = nums[0].size();
        if (r*c != rows*cols) {
            //is that the only case?
            //invalid reshape, return original matrix
            return nums;
        }
        
        vector<vector<int>> m;
        for (int i = 0; i < r; i++) {
            //fill the row
            vector<int> _r;
            for (int j = 0; j < c; j++) {
                _r.emplace_back(rowTraverse(nums, i*c+j));
            }
            m.emplace_back(_r);
        }
        return m;
    }
};

 

以上是关于566. Reshape the Matrix的主要内容,如果未能解决你的问题,请参考以下文章

566. Reshape the Matrix

566. Reshape the Matrix

566. Reshape the Matrix

566. Reshape the Matrix

566. Reshape the Matrix

566. Reshape the Matrix