卡车上的最大单元数(Arrays.sort()重写比较器)
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
int res = 0;
// Arrays.sort(boxTypes, new Comparator<int[]>(){
// @Override
// public int compare(int[] o1, int[] o2){
// if(o1[1] == o2[1]){
// return o2[0] - o1[0];
// }else{
// return o2[1] - o1[1];
// }
// }
// });
Arrays.sort(boxTypes, (o1, o2) -> {
if(o1[1] == o2[1]){
return o2[0] - o1[0];
}else{
return o2[1] - o1[1];
}
});
int index = 0;
while(index < boxTypes.length){
if(boxTypes[index][0] <= truckSize){
res += boxTypes[index][0] * boxTypes[index][1];
truckSize -= boxTypes[index][0];
index++;
}else{
res += truckSize * boxTypes[index][1];
break;
}
}
return res;
}
}