566 Reshape the Matrix

173 阅读1分钟

weekly contest30的第一题。 这是一道送分题。

对于处理下标,我采用了不需要动脑子的方法就是先把数组A的内容保存起来再依次赋值给数组B。这样用了O(MN)空间,很不好。

巧妙的做法是,利用divide和mod:

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

ref: https://discuss.leetcode.com/topic/87851/java-concise-o-nm-time https://discuss.leetcode.com/topic/87853/easy-java-solution