zoukankan      html  css  js  c++  java
  • 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 columnnumber 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.
     1 public class Solution {
     2     public int[][] matrixReshape(int[][] nums, int r, int c) {
     3         int m = nums.length, n = nums[0].length;
     4         if (m * n != r * c) return nums;
     5         
     6         int[][] result = new int[r][c];
     7         int rc = 0, cc = 0;
     8         for (int i = 0; i < m; i ++) {
     9             for (int j = 0; j < n; j++) {
    10                 result[rc][cc++] = nums[i][j];
    11                 if (cc == c) {
    12                     cc = 0;
    13                     rc++;
    14                 }
    15             }
    16         }
    17         return result;
    18     }
    19 }
  • 相关阅读:
    Python GUI编程实例
    Python MySQL事务、引擎、索引及第三方库sqlalchemy
    Python 魔法方法简介
    Python sax模块(SAX解析XML)
    Python minidom模块(DOM写入和解析XML)
    【LOJ】#2432. 「POI2014」代理商 Couriers
    【51nod】1559 车和矩形
    【LOJ】#2430. 「POI2014」沙拉餐厅 Salad Bar
    【LOJ】#2105. 「TJOI2015」概率论
    【BZOJ】1336: [Balkan2002]Alien最小圆覆盖
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6830659.html
Copyright © 2011-2022 走看看