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

43 篇文章 0 订阅
34 篇文章 0 订阅

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值