C# solution: simply iterate all items


  • 0
    B
    public class Solution 
    {
        public int[,] MatrixReshape(int[,] nums, int r, int c) 
        {
            var row = nums.GetLength(0);
            var col = nums.GetLength(1);
    
            if (row * col != r * c) return nums;
    
            var result = new int[r,c];
    
            var originalX = 0;
            var originalY = 0;
    
            for (int i = 0; i < r; i++)
            {
                for(int j = 0; j < c; j++)
                {
                    result[i, j] = nums[originalX, originalY];
                    originalY++;
    
                    if (originalY == col)
                    {
                        originalX++;
                        originalY = 0;
                    }
                }
            }
    
            return result;
        }
    }
    

Log in to reply
 

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