leetcode[Reshape the Matrix]//待整理多种解法

来源:互联网 发布:创意美工设计招聘 编辑:程序博客网 时间:2024/06/01 09:42

解法一:

class Solution {    public int[][] matrixReshape(int[][] nums, int r, int c) {        //首先判断能不能重塑矩阵    if(nums.length == 0) return nums;    int row = nums.length;//代表原矩阵的行数    int col = nums[0].length;//代表原矩阵的列数,因为原二维数组代表的是矩阵,所以二维数组的第二维的长度都是相同的    if(row * col != r * c) return nums;    int[][] res = new int[r][c];    int count = 1;//用一个count来计数,矩阵转换后元素个数是不变的,通过count算出原数组对应的位置    for(int i = 0; i < res.length; i++){    for(int j = 0; j < res[0].length; j++){    //计算当前的count应该对应原数组中的哪一个数    //[[1,2],    // [3,4]]   观察这个    int numsI = 0;    int numsJ = 0;    if(count % col == 0){    numsJ = col - 1;    numsI = count / col - 1;    } else{    numsJ = count % col - 1;    numsI = count / col;    }    //System.out.println("numsI:" + numsI + "  numsJ:" + numsJ);    res[i][j] = nums[numsI][numsJ];        count++;//不要忘了递增count    }    }        return res;    }}


原创粉丝点击