携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
题目
leetcode 1184. 公交站间的距离
环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。 环线上的公交车都可以按顺时针和逆时针的方向行驶。 返回乘客从出发点 start 到目的地 destination 之间的最短距离。
示例:
输入:distance = [1,2,3,4], start = 0, destination = 1
输出:1
解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。
题解
根据题目意思我们可以理解为公交的路线只有顺时针和逆时针的方向,在行驶路线中不能跳过途中的站点。
var distanceBetweenBusStops = function(distance, start, destination) {
if(start > destination){
[start, destination] = [destination, start]
}
const all = distance.reduce((sum, n) => sum + n , 0);
const left = distance.reduce((sum, n, i)=>{
if (i < start || i >= destination) {
return sum;
}
return sum + n
}, 0)
return Math.min(left, all - left)
};
代码详解
首先我们对测试用例进行特殊处理,当起始站点下标大于终止站点下标时我们就要把他变成起始站点小于终止站点的形式,方便我们后续的代码书写。
[start, destination] = [destination, start]
这段代码是技巧型写法,运用到了es5的语法数组的解构赋值。有兴趣的小伙伴可以尝试一下。
接下来计算所有路线的总长度用变量all表示。
const all = distance.reduce((sum, n) => sum + n , 0);
计算长度时也是运用到了es6的语法数组的API reduce。
最后只需要比较顺时针行驶的长度和逆时针行驶的长度即得出最终答案。这道题其实挺简单的,而且在写法上还是有很多思路的。