【LeetCode】566. Reshape the Matrix(重塑矩阵)
题目链接:https://leetcode.com/problems/reshape-the-matrix/description/
问题描述:直接看例子
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:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
解释:给一个矩阵,要求变化成给定的r行c列的矩阵,并输出;否则,输出原矩阵。
例如给定矩阵是3x4,那么可以变化成1x12,12x1,2x6,6x2,4x3,当然也可以和原矩阵相等3x4.总之要求元素个数必须相同。
我的代码:
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int n=nums.length;
int m=nums[0].length;
int arr[][]=new int[r][c];
if(m*n==r*c)
{
int[]num=new int[n*m];
for(int i=0,k=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
num[k]=nums[i][j];
k++;
}
}
for(int i=0,k=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=num[k];
k++;
}
}
return arr;
}
else return nums;
}
}
标准答案:
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int original_r = nums.length;
int original_c = nums[0].length;
if (original_r * original_c == r * c) {
int[][] result = new int[r][c];
for (int i = 0; i < r * c; i++) {
result[i / c][i % c] = nums[i / original_c][i % original_c];
}
return result;
} else {
return nums;
}
}
}
哈哈,标准答案好精简阿,学习了。
日期:2018/2/8-12:31