func matrixReshape(mat [][]int, r int, c int) [][]int {
height, weight := len(mat), len(mat[0])
if r == height && c == weight || height*weight != r*c {
return mat
}
result := make([][]int, r)
cr, cc := 0, 0
for _, row := range mat {
for _, col := range row {
if cc >= c {
cr++
cc %= c
}
if result[cr] == nil {
result[cr] = make([]int, c)
}
result[cr][cc] = col
cc++
}
}
return result
}
这个做法过于模拟,当然还有一些算法上的优化:
Go复制代码
func matrixReshape(nums [][]int, r int, c int) [][]int {
height, weight := len(nums), len(nums[0])
if height*weight != r*c {
return nums
}
result := make([][]int, r)
for i := range result {
result[i] = make([]int, c)
}
for i := 0; i < height*weight; i++ {
result[i/c][i%c] = nums[i/weight][i%weight]
}
return result
}