算法: reshape the matrix

reshape the matrix
// 找到对应新矩阵和原来矩阵行列的关系以及对应的变换
//

class Solution {
    func matrixReshape(_ nums: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
        guard nums.count > 0 else { return nums }
        let m = nums.count
        let n = nums[0].count
        guard m * n == r * c else { return nums }
        var ans = Array(repeating: [Int](repeating: 0, count: c), count: r)
        for currentIndex in 0 ... m * n - 1 {
          // 变换数组的行列索引
            let o_y = currentIndex / n // origin
            let o_x = currentIndex % n
            let n_y = currentIndex / c // new 
            let n_x = currentIndex % c
            ans[n_y][n_x] = nums[o_y][o_x]
        }
        return ans
    }
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/8cf83e033aa1
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞