package Sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DiagonalSort_1329 {
// 1329. Sort the Matrix Diagonally
// 思路:
// 找出所有对角线起点,将每条对角线上的元素放入list,用Colections工具类排序后一次放回对角线
public int[][] diagonalSort(int[][] mat) {
// 第一行的起始点
for(int i=0;i<mat[0].length;i++) {
List<Integer> list=new ArrayList<>();
int col=i; // 列号
int row=0; // 行号
while(col<mat[0].length&&row<mat.length) {
list.add(mat[row++][col++]);
}
Collections.sort(list);
col=i; // 列号
row=0; // 行号
int index=0;
while(col<mat[0].length&&row<mat.length) {
mat[row++][col++]=list.get(index++);
}
}
// 第一列的起始点
for(int i=0;i<mat.length;i++) {
List<Integer> list=new ArrayList<>();
int col=0; // 列号
int row=i; // 行号
while(col<mat[0].length&&row<mat.length) {
list.add(mat[row++][col++]);
}
Collections.sort(list);
col=0; // 列号
row=i; // 行号
int index=0;
while(col<mat[0].length&&row<mat.length) {
mat[row++][col++]=list.get(index++);
}
}
return mat;
}
}
1329. Sort the Matrix Diagonally
最新推荐文章于 2023-02-25 22:41:55 发布