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 }

  

原文地址:https://www.cnblogs.com/masterSoul/p/8134260.html