3
\$\begingroup\$

Please review performance

https://leetcode.com/problems/transpose-matrix/

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]

Example 2:

Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]

Note:

1 <= A.length <= 1000 1 <= A[0].length <= 1000

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    [TestClass]
    public class TransposeMatrix
    {

        /// <summary>
        /// 1 2 3       1 4 7
        /// 4 5 6       2 5 8
        /// 7 8 9       3 6 9
        /// </summary>
        [TestMethod]
        public void Transpose3X3()
        {
            int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } };
            int[][] expected = { new[] { 1, 4, 7 }, new[] { 2, 5, 8 }, new[] { 3, 6, 9 } };
            int[][] output = Transpose(matrix);
            for (int i = 0; i < output.GetLength(0); i++)
            {
                CollectionAssert.AreEqual(expected[i], output[i]);
            }
        }

        [TestMethod]
        public void Transpose2X3()
        {
            int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } };
            int[][] expected = { new[] { 1, 4 }, new[] { 2, 5 }, new[] { 3, 6} };
            int[][] output = Transpose(matrix);
            for (int i = 0; i < output.GetLength(0); i++)
            {
                CollectionAssert.AreEqual(expected[i], output[i]);
            }
        }
        public int[][] Transpose(int[][] A)
        {
            int h = A.GetLength(0);
            int w = A[0].GetLength(0);

            //we need to allocate the matrix as transposed already
            //for example 2x3 should allocate 3x2
            int[][] res = new int[w][];
            for (int i = 0; i < w; i++)
            {
                res[i] = new int[h];
            }

            for (int r = 0; r < h; r++)
            {
                for (int c = 0; c < w; c++)
                {
                    res[c][r] = A[r][c];
                }
            }
            return res;
        }
    }
}
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

You iterate through the same array twice (once while initializing and once while assigning values), you can do both inside the same loop.

for (int i = 0; i < w; i++)
{
    res[i] = new int[h];
    for (int j = 0; j < h; j++)
    {
        res[i][j] = A[j][i];
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.