★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-hzafohbc-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a matrix A
, return the transpose of A
.git
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. github
Example 1:api
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:app
1 <= A.length <= 1000
1 <= A[0].length <= 1000
給定一個矩陣 A
, 返回 A
的轉置矩陣。spa
矩陣的轉置是指將矩陣的主對角線翻轉,交換矩陣的行索引與列索引。 code
示例 1:htm
輸入:[[1,2,3],[4,5,6],[7,8,9]] 輸出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:blog
輸入:[[1,2,3],[4,5,6]] 輸出:[[1,4],[2,5],[3,6]]
提示:
1 <= A.length <= 1000
1 <= A[0].length <= 1000
1 class Solution { 2 func transpose(_ A: [[Int]]) -> [[Int]] { 3 var tmp = Array(repeating: (Array(repeating:0, count: A.count)), count: A[0].count) 4 for i in 0..<A[0].count { 5 for j in 0..<A.count { 6 tmp[i][j] = A[j][i] 7 } 8 } 9 10 return tmp 11 } 12 }
1 class Solution { 2 func transpose(_ A: [[Int]]) -> [[Int]] { 3 if A.count == 0 { 4 return [] 5 } 6 let count = A[0].count 7 var R: [[Int]] = [] 8 for j in 0..<count { 9 var r: [Int] = [] 10 for i in 0..<A.count { 11 r.append(A[i][j]) 12 } 13 R.append(r) 14 } 15 16 return R 17 } 18 }
116ms
1 class Solution { 2 func transpose(_ A: [[Int]]) -> [[Int]] { 3 var result: [[Int]] = [] 4 for i in 0..<A[0].count { 5 result.append([]) 6 for j in 0..<A.count { 7 result[i].append(A[j][i]) 8 } 9 } 10 return result 11 } 12 }
124ms
1 class Solution { 2 func transpose(_ A: [[Int]]) -> [[Int]] { 3 var x = A.count 4 var y = A[0].count 5 var result: [[Int]] = [] 6 7 for i in 0..<y { 8 var list: [Int] = [] 9 for j in 0..<x { 10 list += [A[j][i]] 11 } 12 result += [list] 13 } 14 15 return result 16 } 17 }
128ms
class Solution { func transpose(_ A: [[Int]]) -> [[Int]] { var row = -1 var column = -1 let result = Array(count: A[0].count) { () -> [Int] in row += 1 column = -1 return Array(count: A.count) { () -> Int in column += 1 return A[column][row] } } return result } } public extension Array { public init(count: Int, generator: @escaping() -> Element) { precondition(count >= 0, "arrays must have non-negative size") self.init((0..<count).lazy.map { Element in generator() }) } }