美文网首页
leetcode的每日一题更新(Reshape the Matr

leetcode的每日一题更新(Reshape the Matr

作者: 今天是晴天 | 来源:发表于2017-05-11 08:32 被阅读0次

    题目:给一个二维数组和两个数字,返回一个二维数组,第一个数字代表返回的数组的行,第二个数字代表列。

    思路:刚开始想逻辑想不明白,可能是想循环一下搞定,但是不行,只能在循环外面创建两个变量来控制要返回的数组的接收,思路很清晰就是说不上来,直接附代码:

    public int[][] matrixReshape(int[][] nums, int r, int c) {
            if(nums==null)return null;
            if(nums.length*nums[0].length!=r*c)return nums;
            int[] tem=new int[nums.length*nums[0].length];
            int carry=0;
            int hang=0;
            int[][] result=new int[r][c];
            for(int i=0;i<nums.length;i++){
                for(int j=0;j<nums[0].length;j++){
                    result[hang][carry]=nums[i][j];
                    if(carry==c-1){
                        carry=0;
                        hang++;
                        continue;
                    }
                    carry++;
                }
            }
            return result;
        }
    

    看看高手的解题方法:
    和我的差不多,就是用了一些取巧的办法:

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int n = nums.length, m = nums[0].length;
        if (r*c != n*m) return nums;
        int[][] res = new int[r][c];
        for (int i=0;i<r*c;i++) 
            res[i/c][i%c] = nums[i/m][i%m];
        return res;
    }
    

    相关文章

      网友评论

          本文标题:leetcode的每日一题更新(Reshape the Matr

          本文链接:https://www.haomeiwen.com/subject/oxwntxtx.html