C# "beats 99.36%" Solution

  • 0

    Basically see if we can create new matrix, then allocate memory and loop assigning by absolute position since we're told to read left to right. I believe it's O(nm) space (size of newly allocated matrix) & O(nm) time - we loop over all elements once.

        public int[,] MatrixReshape(int[,] nums, int r, int c) {
            var r2 = nums.GetLength(0);
            var c2 = nums.GetLength(1);
            // if dimensions don't align then return
            if (r2 *c2 != r * c) return nums;
            // create new matrix shape
            int[,] result = new int[r,c];
            // loop over all rows
            for(var i = 0; i < r2; i++){
                // loop over all columns
                for(var j = 0; j < c2; j++){
                    // position is L-to-R position with (0,0) as index 0.  multiply out by c2 as 
                    // that's the number of columns we've skipped by being in row i and add current row offset j
                    var position = (i*c2) + j;
                    // absolute position integer division by new column size, c, gives us new row number (floor assumed)
                    // absolute position mod column size, c, gives us offset into current row aka column #
                    result[position / c, position % c] = nums[i,j];
            return result;

Log in to reply

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