美文网首页
IOS 算法(基础篇) ----- 转置矩阵

IOS 算法(基础篇) ----- 转置矩阵

作者: ShawnAlex | 来源:发表于2021-02-25 10:49 被阅读0次

    给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。
    矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。

    exp

    例子

    输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
    输出:[[1,4,7],[2,5,8],[3,6,9]]

    输入:matrix = [[1,2,3],[4,5,6]]
    输出:[[1,4],[2,5],[3,6]]

    解题思路

    题意不难理解, 其实就是把 A[i][j] 转成 A[j][i]的操作

    代码

    未翻译版

        func transpose(_ matrix: [[Int]]) -> [[Int]] {
    
            var temp = [[Int]](repeating: [Int](repeating: 0, count: matrix.count), count: matrix[0].count)
            
            for i in 0..<matrix.count {
                for j in 0..<matrix[i].count {
                    temp[j][i] = matrix[i][j]
                }
            }
            
            return temp
        }
    

    翻译版

        func transpose(_ matrix: [[Int]]) -> [[Int]] {
    
            // 定义容器数组存放结果, n x m, 初始全设置0
            var temp = [[Int]](repeating: [Int](repeating: 0, count: matrix.count), count: matrix[0].count)
            
            // 循环, 将 matrix[i][j] 赋给 temp[j][i]
            for i in 0..<matrix.count {
                for j in 0..<matrix[i].count {
                    temp[j][i] = matrix[i][j]
                }
            }
            
            // 返回结果
            return temp
    
        }
    

    题目来源:力扣(LeetCode) 感谢力扣爸爸 :)
    IOS 算法合集地址

    相关文章

      网友评论

          本文标题:IOS 算法(基础篇) ----- 转置矩阵

          本文链接:https://www.haomeiwen.com/subject/rimyfltx.html