zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    [CEOI2008] order
    Atcoder 2373 Cookie Exchanges
    [POI2011]ROT-Tree Rotations
    bzoj 5216: [Lydsy2017省队十连测]公路建设
    bzoj 5215: [Lydsy2017省队十连测]商店购物
    Codeforces 961 E Tufurama
    [九省联考2018] 秘密袭击coat
    Codeforces 961 D Pair Of Lines
    [八省联考2018] 劈配
    [九省联考2018]一双木棋chess
  • 原文地址:https://www.cnblogs.com/agentgamer/p/9771769.html
Copyright © 2011-2022 走看看