题目名称

环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。

环线上的公交车都可以按顺时针和逆时针的方向行驶。

返回乘客从出发点 start 到目的地 destination 之间的最短距离。

示例

输入:distance = [1,2,3,4], start = 0, destination = 1

输出:1

输入:distance = [1,2,3,4], start = 0, destination = 2

输出:3

题解

这道题主要考察我们对于数组的操作,根据题目,我们可以得知 公交可以按照顺序针和逆时针运动,也就是说方向并不固定,其次就是没有规定 出发点一定在目的站的前面(这个是重点)

所以这个时候就有两种类型,一种是出发点在目的地前面,还有一种是出发点在目的地的后面

针对第一种,我们可以先计算出所有站的距离的和 total,然后在计算出两站之间顺时针的距离 dis,然后对比 distotal - dis 的距离哪个最小

第二种同样,只不过是将出发点和目的地翻转一下

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var distanceBetweenBusStops = function(distance, start, destination) {
if(start === destination) return 0
let total = distance.reduce((total, item) => {
return total + item
}, 0)
let dis = 0
if(destination < start) {
dis = distance.slice(destination, start).reduce((total, item) => {
return total + item
}, 0)
} else {
dis = distance.slice(start, destination).reduce((total, item) => {
return total + item
}, 0)
}
return Math.min(dis, total - dis)
};