问题:
方法:
首先理解题意,本质还是排序,只是index的遍历比一维数组和二维数组特殊是沿着斜线,所以只要特殊处理index的遍历即可,然后再斜轴上进行快排。下面的算法还可以优化空间复杂度,不用分配空间。
fun diagonalSort(mat: Array<IntArray>): Array<IntArray> {
val list = mutableListOf<Int>()
for (index in mat.indices) {
list.clear()
var i = 0
while (index+i <= mat.lastIndex && i <= mat[0].lastIndex) {
list.add(mat[index+i][i])
i++
}
list.sort()
i = 0
while (index+i <= mat.lastIndex && i <= mat[0].lastIndex) {
mat[index+i][i] = list[i]
i++
}
}
for (index in 1..mat[0].lastIndex) {
list.clear()
var i = 0
while (i <= mat.lastIndex && i + index <= mat[0].lastIndex) {
list.add(mat[i][i + index])
i++
}
list.sort()
i = 0
while (i <= mat.lastIndex && i + index <= mat[0].lastIndex) {
mat[i][i + index] = list[i]
i++
}
}
return mat
}
有问题随时沟通