566. 重塑矩阵

题目链接:https://leetcode-cn.com/problems/reshape-the-matrix/

执行用时:76 ms, 在所有 Swift 提交中击败了100.00%的用户
内存消耗:13.6 MB, 在所有 Swift 提交中击败了97.37%的用户

1.每次内循环判断新的矩阵宽度是否符合要求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
func matrixReshape(_ mat: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
let m = mat.count, n = mat[0].count
if m*n != r*c {
return mat
}
var res : [[Int]] = []
var current : [Int] = []
for i in 0 ..< m {
for j in 0 ..< n {
current.append(mat[i][j])
if current.count == c {
res.append(current)
current = []
}
}
}
return res
}
}

2.取出全部再放回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
func matrixReshape(_ mat: [[Int]], _ r: Int, _ c: Int) -> [[Int]] {
var res = [[Int]].init(repeating: [], count: r)
let m = mat.count, n = mat[0].count
if m*n != r*c {
return mat
}
var warehouse = [Int]()
for i in 0 ..< m {
for j in 0 ..< n {
warehouse.append(mat[i][j])
}
}
var index = 0;
for i in 0 ..< r {
for j in 0 ..< c {
res[i].append(warehouse[index])
index += 1
}
}
return res
}
}

566. 重塑矩阵
https://pisces34.github.io/2021/09/26/leetcode/556/
发布于
2021年9月26日
许可协议