Java Concise O(nm) time

  • 38
    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;

  • 1

    why cannot use k=r*i+j? I think it is equivalent to k++ for ever loop. However, it shows that index out of bounds.

  • -4

    Isn't it supposed to be
    if (r*c != n+m) return nums;

  • 0

    If i,j are both negative, there will be problems......

  • -2

    I don't know why, but the runtime of your code is actually slow
    Now I know why, Because I' submit this from mainland China!
    Fuck GFW

  • 0

    Python version

    class Solution(object):
        def matrixReshape(self, nums, r, c):
            row, col = len(nums), len(nums[0])
            res = [[None] * c for _ in xrange(r)]
            if row*col != r*c:
                return nums
                for i in range(r*c):
                return res

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.