• leetcode--Algorithm--Array_Part 1 Easy- 566 Reshape the Matrix


    LeetCode Array Part 1 Easy

    2017-12-28  10:01:31

    566. Reshape the Matrix 重塑矩阵

    https://leetcode.com/problems/reshape-the-matrix/description/

    要求是 实现 Matlabe 中的 reshape函数。对二维数组大小重新分配。

    方法:

      1. 先把原数组拉直,变成一条直线,然后再组成新的数组。

      先判断给定数组能否重塑成给定的大小,就是看两者的元素总数是否相同,直接行数乘以列数,

      然后新建一个目标大小的数组,并开始遍历,对于每个位置,先转为拉直后的一维坐标,然后再算出在原数组中的对应位置赋值过来即可。

      

     1 class Solution {
     2     public int[][] matrixReshape(int[][] nums, int r, int c) {
     3         int m = nums.length, n = nums[0].length;
     4         
     5         // 重置矩阵为任意维度 前提是矩阵里的元素总数不变
     6         if(r*c != m*n) return nums;
     7         int[][] res = new int[r][c];
     8         // core code
     9         for(int i = 0; i < r*c; i++)
    10             res[i/c][i%c] = nums[i/n][i%n];
    11         
    12         return res;
    13     }
    14 }

      

  • 相关阅读:
    jquery $.each遍历json数组方法
    JQuery插件编写
    创建JAVASCRIPT对象3种方法
    微信开发流程
    有关索引那点事
    获取数据库内所有的表和表内字段的信息
    asp.net MVC4 异步文件上传
    QT学习:01 工程文件详解
    QT学习:00 介绍
    Linux 系统编程 学习 总结
  • 原文地址:https://www.cnblogs.com/masterSoul/p/8134260.html
Copyright © 2020-2023  润新知