首页 > 解决方案 > 航班清单

问题描述

我有这个问题要解决。

您将获得一份航班开始和结束时间的列表。确定同时在空中的最大飞机数量

例子

  {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)

标签: javascript

解决方案


你可以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));


推荐阅读