给定 n 个学生( 1 到 n 编号)以及他们的考试成绩,这里有两个关键字,考试成绩以及学生学号。根据第一关键字对数组进行排序(降序),如果第一关键字相同则根据第二关键字进行排序(升序).
样例
给出 [[2,50],[1,50],[3,100]],
返回 [[3,100],[1,50],[2,50]]
解题思路:
注意写Comparator接口时,返回-1的条件即为期望排序结果,如本题中返回-1的条件即是升序
复杂易懂版本:
public class Solution {
/**
* @param array: the input array
* @return: the sorted array
*/
public int[][] multiSort(int[][] array) {
// Write your code here
Arrays.sort(array, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
//根据考试成绩降序
if(a[1] > b[1])
return -1;
else if(a[1] < b[1])
return 1;
else{ //根据学号升序
if(a[0] < b[0])
return -1;
else if(a[0] > b[0])
return 1;
else
return 0;
}
}
});
return array;
}
}
简略老鸟版本:
public class Solution {
/**
* @param array: the input array
* @return: the sorted array
*/
public int[][] multiSort(int[][] array) {
// Write your code here
Arrays.sort(array, new Comparator<int[]>(){
public int compare(int[] l, int[] r) {
if (l[1] != r[1]) {//根据考试成绩降序
return r[1] - l[1];
}
//根据学号升序
return l[0] - r[0];
}
});
return array;
}
}

本文介绍了一种根据学生考试成绩降序及学号升序的多关键字排序算法实现,通过自定义Comparator接口,详细展示了如何使用Java进行数组排序,包括复杂易懂版本和简洁的老鸟版本代码。
971

被折叠的 条评论
为什么被折叠?



