0
点赞
收藏
分享

微信扫一扫

数据结构与算法之LeetCode-1184. 公交站间的距离 - 力扣(LeetCode)


​​1184. 公交站间的距离 - 力扣(LeetCode)​​

  • 判断start和destination的大小,for循环从start到destination累加,并存入遍历过的set中-》顺时针 clockwise
  • 在遍历一次所有的distance,排除访问过的内容-》 逆时针 - anti-clockwise
  • 取close wise和 anti-clockwise 中最小的值

/**
* @param {number[]} distance
* @param {number} start
* @param {number} destination
* @return {number}
*/
var distanceBetweenBusStops = function(distance, start, destination) {
let clockwise = 0, antiClockwise = 0,n=distance.length,set = new Set();
// const swap = (start,destination)=>{
// let temp = start;
// start = destination;
// destination = temp;
// }

if(start>destination){
//swap(start,destination)
[start,destination] = [destination,start]
}

for(let i=start;i<destination;i++){
clockwise += distance[i]
set.add(i)
}

for(let i=0;i<n;i++){
if(!set.has(i)){
antiClockwise+=distance[i]
set.add(i)
}
}

return Math.min(clockwise,antiClockwise)
};

执行结果:通过

执行用时:60 ms, 在所有 JavaScript 提交中击败了60.26%的用户

内存消耗:42 MB, 在所有 JavaScript 提交中击败了5.13%的用户

通过测试用例:37 / 37

改进
  • 不需要保存访问过的节点,直接在一次遍历中完成

/**
* @param {number[]} distance
* @param {number} start
* @param {number} destination
* @return {number}
*/
var distanceBetweenBusStops = function(distance, start, destination) {
let res = 0;
// const swap = (start,destination)=>{
// let temp = start;
// start = destination;
// destination = temp;
// }

if(start>destination){
//swap(start,destination)
[start,destination] = [destination,start]
}

let antiClockwise = 0;
for(let i=0;i<distance.length;i++){
if(start<=i&&i<destination){
res += distance[i]
}else{
antiClockwise += distance[i]
}

}
return Math.min(res,antiClockwise)
};

执行结果:通过

执行用时:60 ms, 在所有 JavaScript 提交中击败了60.26%的用户

内存消耗:40.8 MB, 在所有 JavaScript 提交中击败了100.00%的用户

通过测试用例:37 / 37

参考链接

​​1184. 公交站间的距离 - 力扣(LeetCode)​​


举报

相关推荐

0 条评论