javascript - 航班清单
问题描述
我有这个问题要解决。
您将获得一份航班开始和结束时间的列表。确定同时在空中的最大飞机数量
例子
{start:4, end:9},
{start:2, end:5},
{start:17, end:20},
{start:10, end:21},
{start:9, end:18},
return 3
如您所见,我必须返回 3,因为同时空中有三架飞机。start:9, end:18 and start:10, end:21 and start:17, end:20
那是三架飞机同时在空中。
这是我的代码
const arr = [
{start:4, end:9},
{start:2, end:5},
{start:17, end:20},
{start:10, end:21},
{start:9, end:18},
]
const flights = flite => {
let final = []
flite.sort((a,b) => a.start - b.start)
for(let i = 0; i < flite.length; i++) {
let st = flite[i]
if(st.end > st.start) return final.push(st.start)
}
return final
}
flights(arr)
解决方案
你可以reduce
像下面这样使用,你会得到你的结果。
const arr = [
{start:4, end:9},
{start:2, end:5},
{start:17, end:20},
{start:10, end:21},
{start:9, end:18},
];
const flights = flite => {
// reduce will iterate through each value and produce single result.
// reduce has two params, callback function and initialValue : optional.
// here I have call back function (a, i) => {...}
// add initialValue = 0, so for first iteration it will have a = 0.
// inside callback function filtering array with flight start time between current timing's start and end. And returning max value between a and filter.length
return flite.reduce((a, i) => Math.max(a, flite.filter(x => x.start >= i.start && x.start <= i.end).length) , 0);
}
console.log(flights(arr));
推荐阅读
- javascript - 需要最佳方法来实现游戏中敌人事件的时间线和迭代间隔
- r - 从 R 3.6 升级到 R 4.0 时,如何将 R 指向正确版本的 curl?
- powerbi - Power BI - DAX RANKX - 如何考虑切片器?
- postgresql - 安装自定义科目表模块时出现数据库错误
- php - 编辑树枝文件后如何重建网站?
- javascript - 在拖动之前更改元素href
- python-3.x - GARCH Variance 的方差协方差矩阵
- python - 如何修复python中'else:'的'e'上的语法错误 - discord.py
- ethereum - NFT——区块链上实际存储了什么来代表数字资产?
- css - 标题有边框,但没有背景?