• 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;
        }
    };
  • 相关阅读:
    hdu-5492 Find a path(dp)
    hdu-5493 Queue(二分+树状数组)
    bzoj-2243 2243: [SDOI2011]染色(树链剖分)
    codeforces 724
    codeforces 422A A. Borya and Hanabi(暴力)
    codeforces 442C C. Artem and Array(贪心)
    codeforces 442B B. Andrey and Problem(贪心)
    hdu-5918 Sequence I(kmp)
    poj-3739. Special Squares(二维前缀和)
    hdu-5927 Auxiliary Set(树形dp)
  • 原文地址:https://www.cnblogs.com/agentgamer/p/9771769.html
Copyright © 2020-2023  润新知