解题思路
题目要求返回最大的单元,可以将数组按照单元格最大的降序排序。箱子数量之和不大于truckSize就可以。
1.可以将数组第二项进行排序;
2.可以用map来存储数据
关于第二点,本打算直接用字符串作为key的,但是示例中有重复项。所以就用类似于桶的模式存储数据,即
{
5:[1,2,3]
}
代码
var maximumUnits = function(boxTypes, truckSize) {
const len = boxTypes.length;
let m = new Map();
let units = [];
for(const box of boxTypes){
if(m.get(box[1])){
m.set(box[1],[...m.get(box[1]),box[0]])
}else{
m.set(box[1],[box[0]])
}
units.push(box[1]);
}
let sum = 0,i = 0,j = 0;
units = units.sort((a,b)=>b-a);
while(i < len){
const val = m.get(units[i]);
const temp = val.reduce((pre,next)=>{return pre + next },0)
if(truckSize - j >= temp){
j += temp;
sum += units[i] * temp;
i+= val.length;
}else{
break;
}
}
const dist = truckSize - j;
sum += units[i] ? dist * units[i] : 0;
return sum;
};
const boxTypes = [[1,3],[5,5],[2,5],[4,2],[4,1],[3,1],[2,2],[1,3],[2,5],[3,2]], truckSize = 35
const boxTypes1 = [[1,3],[2,2],[3,1]], truckSize1 = 4;
const boxTypes2 = [[5,10],[2,5],[4,7],[3,9]], truckSize2 = 10;
优化
看了题解,发现二维数组可以直接进行排序,因此优化为以下代码
const maximumUnits2 = (boxTypes, truckSize)=>{
boxTypes.sort((a,b)=>b[1]-a[1])
let count = 0;
for(const box of boxTypes){
if(box[0] < truckSize){
//0表示箱子数量,1表示箱子里装的单元数
count += box[0] * box[1];
truckSize -= box[0];
}else{
count += truckSize * box[1];
return count;
}
}
return count;
}
//console.log(sortArr(boxTypes));
console.log('--result--',maximumUnits2(boxTypes2, truckSize2));
总结
二维数组排序,要试着尝试,尝试,尝试