leetcode 566 Reshape the Matrix 重塑矩阵

题目链接:https://leetcode.com/problems/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 **column **number 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:

Therow-traversingof 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.

题目大意:

简单题)给一个矩阵,矩阵由若干数组组成,给一对行 与列的值,要求将数组变换成给定行列大小的矩阵,称之为 reshape

解题方法(java语言):

方法一:将所给数组转为一维数组,在开辟一个二维数组,将一维数组的各个数字存进去(队列的思想)

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        if(row*col!=r*c||nums.length==0){return nums;}
        int[] arr1 = new int[row*col];
        int k=0;
        for(int i=0;i

方法二:思想同上,用了队列而已,在这里可以熟悉一下java中队列的操作

操作 说明 备注
add 增加一个元素 如果队列已满,则抛出一个IIIegaISlabEepeplian异常
remove 移除并返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException异常
element 返回队列头部的元素 如果队列为空,则抛出一个NoSuchElementException 异常
offer 添加一个元素并返回true 如果队列已满,则返回false
poll 移除并返问队列头部的元素 如果队列为空,则返回null
peek 返回队列头部的元素 如果队列为空,则返回null
put 添加一个元素 如果队列满,则阻塞
take 移除并返回队列头部的元素 如果队列为空,则阻塞
class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        if(row*col!=r*c){return nums;}
        Queue queue = new LinkedList<>();//创建一个队列
        for(int i=0;i

方法三:方法三:用两个变量来记录当前所在行列,不需要额外的二维数组空间,直接将其放入


class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        if(row==0||row*col!=r*c){return nums;}
        int[][] arr = new int[r][c];
        int curRow=0,curCol=0;//定义两个变量,记录当前行与列
        for(int i=0;i

方法四:定义一个比变量k,用k去记录当前所在位置,k/c和k%c去找到当前行与列

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {
        if(nums.length*nums[0].length!=r*c||nums.length==0){return nums;}
        int[][] arr = new int[r][c];
        int k=0;
        for(int i=0;i

你可能感兴趣的:(leetcode 566 Reshape the Matrix 重塑矩阵)