題目地址:
https://leetcode.com/problems/transpose-matrix/
給定一個矩陣,求其轉置。
注意,給出的矩陣未必是方陣,所以要另外開一個二維數組返回。代碼如下:
public class Solution {
public int[][] transpose(int[][] A) {
if (A == null || A.length == 0 || A[0].length == 0) {
return A;
}
int[][] res = new int[A[0].length][A.length];
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A[0].length; j++) {
res[j][i] = A[i][j];
}
}
return res;
}
}
時空複雜度。