版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/85230921
给定 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;
}
}