题目链接
https://leetcode.cn/problems/sort-the-students-by-their-kth-score/
题目大意
将某一列按照从大到小排序,其余列依据这一列的排列顺序做相应的变化
通过代码 Java
方法一 手写选择排序
class Solution {
public int[][] sortTheStudents(int[][] score, int k) {
//m 学生人数
int m = score.length;
//n 场考试
int n = score[0].length;
//选择排序
//m 个学生,进行 m-1轮排序
int tmpIndex;
int tmp;
for (int i = 0; i < m - 1; i++) {
tmpIndex = i;
for (int j = i + 1; j < m; j++) {
if (score[tmpIndex][k] < score[j][k]) {
tmpIndex = j;
}
}
if (tmpIndex != i) {
for (int j = 0; j < n; j++) {
tmp = score[tmpIndex][j];
score[tmpIndex][j] = score[i][j];
score[i][j] = tmp;
}
}
}
return score;
}
}
方法二
Arrays.sort()
class Solution {
public int[][] sortTheStudents(int[][] score, int k) {
Arrays.sort(score, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o2[k] - o1[k];
}
});
return score;
}
}
Arrays.sort() + lambda表达式
class Solution {
public int[][] sortTheStudents(int[][] score, int k) {
Arrays.sort(score, (a, b) -> b[k] - a[k]);
return score;
}
}