小C的外卖超时判断-题解

91 阅读1分钟

#青训营笔记创作活动

小C点了一个外卖,并且急切地等待着骑手的送达。她想知道她的外卖是否超时了。

已知小C在时刻 t1 点了外卖,外卖平台上显示的预计送达时间为 t2,而实际送达时间为 t3。需要判断外卖是否超时。如果外卖超时,则输出 "Yes";否则输出 "No"

实际送达时间与预计送达时间在 2 小时之内。

思路:分割时间,转换成分钟数,注意处理跨天的情况。跨天的情况需要加 1440 分钟。

js版本代码

function timeTrans(str) {
    const [hours, minutes] = str.split(':').map(Number);
    // console.log(hours, minutes)
    return hours * 60 + minutes

}


function solution(t1, t2, t3) {
    // write code here
    let tt1 = timeTrans(t1)
    let tt2 = timeTrans(t2)
    let tt3 = timeTrans(t3)

    if (tt1 > tt2) {
        tt2 += 1440
    }
    if (tt1 > tt3) {
        tt3 += 1440
    }

    // 判断是否超时
    if (tt2 < tt3 && ((tt3 - tt2) <= 120)) {
        return "Yes"
    }
  

    return "No";
}

function main() {
    console.log(solution("18:00", "19:05", "19:05") === "No");
    console.log(solution("23:00", "00:21", "00:23") === "Yes");
    console.log(solution("23:05", "00:05", "23:58") === "No");
}

main();

python 版本

def time_trans(time_str):
    hours, minutes = map(int, time_str.split(':'))
    return hours * 60 + minutes

def solution(t1: str, t2: str, t3: str) -> str:
    # write code here
    tt1 = time_trans(t1)
    tt2 = time_trans(t2)
    tt3 = time_trans(t3)

    if tt1 > tt2:
        tt2 += 1440
    if tt1 > tt3:
        tt3 += 1440

    # 判断是否超时
    if tt2 < tt3 and (tt3 - tt2) <= 120:
        return "Yes"
    
    return "No"



if __name__ == '__main__':
    print(solution("18:00", "19:05", "19:05") == 'No')
    print(solution("23:00", "00:21", "00:23") == 'Yes')
    print(solution("23:05", "00:05", "23:58") == 'No')