C# code, O(rc)


  • 0
    P
    public int[,] MatrixReshape(int[,] nums, int r, int c) {
                int row = nums.GetLength(0);
                int col = nums.GetLength(1);
                if (r * c != row * col)
                    return nums;
                int[,] res = new int[r, c];
                int x = 0, y = 0;
                for (int i = 0; i < r; i++)
                {
                    for (int j = 0; j < c; j++)
                    {
                        if(y >= col)
                        {
                            x++;
                            y = 0;
                        }
                        res[i, j] = nums[x, y];
                        y++;
                    }
                }
                return res;
        }
    

Log in to reply
 

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