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 }
  • 相关阅读:
    博客园随笔备份Java脚本
    vue 获取 referer
    EntityFramework的天坑
    清空stringbuilder
    相关的验证的正则表达式
    清空StringBuilder的三种方法及效率
    oracle中的字符串函数详解
    浅谈C# application.DoEvent作用
    C# 简单Tcp通信demo
    C#中http请求下载的常用方式demo
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6830659.html
Copyright © 2011-2022 走看看