★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10588964.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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
给定一个矩阵 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]]
提示:
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() }) } }
请发表评论