算法: 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
    }
}

你可能感兴趣的:(算法: reshape the matrix)