zoukankan      html  css  js  c++  java
  • LeetCode 566. Reshape the Matrix

    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.

    Example 2:

    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.

    Note:

      1. The height and width of the given matrix is in range [1, 100].
      2. The given r and c are all positive.

    题目不难理解,实现MATLAB中reshape函数,也就是改变矩阵维度但是不改变矩阵元素数目,只需要寻找某个元素在新旧矩阵中行列的表示方法就行

    注意:用二维vector时,若使用二维数组的方式访问时,一定要先初始化,否则会出现访问越界的情况,代码如下:

     1 class Solution {
     2 public:
     3     vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
     4         //元素总数确定,直接寻找新矩阵和旧矩阵元素行列之间的关系即可
     5         int row = nums.size(), col = nums[0].size();
     6         int all = row * col;
     7         vector<vector<int>> res(r, vector<int>(c, 0));
     8         if (r * c != col * row)
     9             return nums;
    10         for (int i = 0; i < all; i++)
    11             res[i/c][i%c] = nums[i/col][i%col];
    12         return res;
    13     }
    14 };
  • 相关阅读:
    vue之路由的命名视图实现经典布局
    vue之路由的嵌套 子路由
    AngularJS阻止事件冒泡$event.stopPropagation()
    Vue之路由规则中定义参数 传参方式2 params
    前台页面中的Cookie存取删除,以及Cookie的跨域问题
    关于Cookie中的Expire问题和删除Cookie那点事儿
    4-索引中的那些操作
    3-在字符串内插中的神奇用法
    2-for循环之特别的写法与神奇的Override
    1-在C#中的数字 int double
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/7887573.html
Copyright © 2011-2022 走看看