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_ 学习笔记(hello world)
    python_ 学习笔记(运算符)
    MySQL-联合查询
    MySQL-date和datetime
    python_ 学习笔记(基本数据类型)
    python_ 学习笔记(基础语法)
    Visaul Studio 常用快捷键的动画演示
    IIS日志-网站运维的好帮手
    浅谈反射机制
    SQL Server 数据库优化文章
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6830659.html
Copyright © 2011-2022 走看看