zoukankan      html  css  js  c++  java
  • 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 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. if (nums.GetLength(0) * nums.GetLength(1) != r * c) {
    4. return nums;
    5. }
    6. Queue<int> list = new Queue<int>();
    7. for (var i = 0; i < nums.GetLength(0); i++) {
    8. for (var j = 0; j < nums.GetLength(1); j++) {
    9. list.Enqueue(nums[i, j]);
    10. }
    11. }
    12. int[,] newMatrix = new int[r, c];
    13. for (var i = 0; i < newMatrix.GetLength(0); i++) {
    14. for (var j = 0; j < newMatrix.GetLength(1); j++) {
    15. newMatrix[i, j] = list.Dequeue();
    16. }
    17. }
    18. return newMatrix;
    19. }
    20. }







  • 相关阅读:
    JDBC连接MySQL数据库及演示样例
    Devstack: A copy of worked local.conf I&#39;m sharing with you.
    jQuery Easy UI Droppable(放置)组件
    指针
    “cvSnakeImage”: 找不到标识符
    按键控制电机显示速度
    验证(Verification)与确认(Validation)的差别
    转换流--OutputStreamWriter类与InputStreamReader类
    特征选择方法之信息增益
    Angular和jQuery的ajax请求的差别
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/03bdc1ef1b264c68d24a21e92674278b.html
Copyright © 2011-2022 走看看