简体   繁体   中英

Transpose 2D Matrix in Java - Time & Space Complexity?

Here's my algorithm / approach for transposing a 2D Matrix on the main diagonal.

Before:

a L M d 
b G c N 
H K e F 
I J O P 

After:

a b H I 
L G K J 
M c e O 
d N F P 

My code:

public class Matrix {

    static String[][] matrix = {

            {"a", "L", "M", "d"},
            {"b", "G", "c", "N"},
            {"H", "K", "e", "F"},
            {"I", "J", "O", "P"}
    };

    public void transpose(String[][] matrix) {
       String[][] transposedArray = new String [4][4];
       for (int row =0; row < 4; row ++) {
           for (int col = 0; col < 4; col++) {
               transposedArray[row][col] = matrix[col][row];  
           }
       }
    }
}

What is the time & space complexity of this approach?

Is there a better optimal solution?

The time complexity for your algorithm will be O(n). If you pass in a 16 element matrix (4x4) it will take approximately 16 units of time. If you pass in a 100 element matrix (10x10) it will take approximately 100 units of time.

The space complexity will be O(n) - in other words the amount of memory required is approximately proportional to the input matrix size. In your case, you could say it would be O(2n) - since it will take approximately twice the space of your input matrix (inc the input matrix).

The reason I say approximate is that there is minimal additional time and space required for loops and their variables, but these become insignificant for any reasonably sized input matrix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM