Reshape the Matrix(java)

题目在这里

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

就是让写一个函数,入参是一个二维数组,给这个二维数组重新指定一个行和列,比如之前是三行两列,传入新的行数和列数,比如两行三列,看是否能重新排列。

我先写了一个java的程序:

    public static int[][] matrixReshape(int[][] nums, int r, int c) {
        //先算出这个数组的行和列
        int nums_r = nums.length;
        int nums_c = nums[0].length;

        //相乘相等则往下走,否则返回原函数
        if (nums_c*nums_r == r*c){
            int[][] ret = new int[r][c];
            int[] temp = new int[r*c];
            //先把二维数组转换成一维数组
            for (int i = 0;i<nums_r;i++){
                System.out.println("i = " + i);
                for (int j = 0;j<nums_c;j++){
                    temp[i*nums_c+j] = nums[i][j];
                }
            }
            System.out.println("temp = " + Arrays.toString(temp));
            
            
            //然后再把以为数组重新放入新的二维数组中
            for (int i = 0;i<r;i++){
                for (int j = 0;j<c;j++){
                    ret[i][j] = temp[i*c+j];
                }
            }

            return ret;


        }else {
            return nums;
        }

    }

 然后百度了一个答案比我这简单 直接就赋值了

地址在这http://blog.csdn.net/kangbin825/article/details/71075651

 

posted on 2017-05-24 17:05  甄仲琪  阅读(448)  评论(0)    收藏  举报

导航