LeetCode 867 矩陣轉換 - Go 實現
阿新 • • 發佈:2021-02-06
技術標籤:ACM
Golang刷LeetCode 867. 轉置矩陣
給定一個矩陣 A, 返回 A 的轉置矩陣。
矩陣的轉置是指將矩陣的主對角線翻轉,交換矩陣的行索引與列索引。
示例 1:
輸入:[[1,2,3],[4,5,6],[7,8,9]]
輸出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
輸入:[[1,2,3],[4,5,6]]
輸出:[[1,4],[2,5],[3,6]]
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/transpose-matrix
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
AC 程式碼
func transpose(A [][]int) [][]int {
// 交換行和列索引
result:=make([][]int,len(A[0]))
for i,_:=range result {
result[i]=make([]int,len(A))
}
for i:=0;i<len(A);i++ {
for j:=0;j<len(A[0]);j++ {
result[j][i]=A[i][j]
}
}
return result
}