leet (Reshape the Matrix)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84560675

Title:Reshape the Matrix    566

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/array-partition-i/

1. 采用了一位数组作为中间的过度,先将原来的二维数组存储到过度的一维数组中,然后将过度的一维数组存储到二维数组中

时间复杂度:O(n^2),嵌套遍历。

空间复杂度:O(n),申请的最长空间长度为r * c。

    /**
     * 采用了一位数组作为中间的过度,先将原来的二维数组存储到过度的一维数组中,然后将过度的一维数组存储到二维数组中
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape(int[][] nums, int r, int c) {

        int row = nums.length;
        int column = nums[0].length;
        if (r * c != row * column) {
            return nums;
        }

        int k = 0;
        int tmp[] = new int[row * column];
        int result[][] = new int[r][c];

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < column; j++) {
                tmp[k++] = nums[i][j];
            }
        }

        int kk = 0;
        for(int i = 0; i < r; i++) {
            for(int j = 0; j < c; j++) {
                result[i][j] = tmp[kk++];
            }
        }

        return result;

    }

2.整除为行,求余为列

时间复杂度:O(n),一次一层遍历,最长遍历为r * c。

空间复杂度:O(n),申请的最长空间长度为r * c。

    /**
     * 整除为行,求余为列
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape1(int[][] nums, int r, int c) {

        int row = nums.length;
        int column = nums[0].length;
        if (r * c != row * column) {
            return nums;
        }

        int result[][] = new int[r][c];

        for(int i = 0; i < r * c; i++) {
            result[i / c][i % c] = nums[i / column][i % column];
        }

        return result;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84560675