小C的外卖超时判断 | 豆包MarsCode AI刷题

96 阅读2分钟

小C的外卖超时判断 | 豆包MarsCode AI刷题

小C的外卖超时判断 - MarsCode

摘要

本文介绍了如何判断小C的外卖是否超时。给定下单时间、预计送达时间和实际送达时间,判断在跨日情况下外卖是否超时。通过将时间转换为24小时制并比较时间差来实现。本文提供Python和Go的代码实现。

问题描述

给定下单时间 t1t1,预计送达时间 t2t2 和实际送达时间 t3t3,判断实际送达时间是否超过预计送达时间。如果 t3t3 超过 t2t2,则外卖视为超时。

示例

  • 输入:t1 = "18:00", t2 = "19:05", t3 = "19:05" 输出:"No"

  • 输入:t1 = "23:00", t2 = "00:21", t3 = "00:23" 输出:"Yes"

  • 输入:t1 = "23:05", t2 = "00:05", t3 = "23:58" 输出:"No"

原理分析

1. 时间解析与跨日处理

将时间 t1t1t2t2t3t3 分解为小时和分钟,并根据下单时间 t1t1 判断是否需要将 t2t2t3t3 的时间跨日调整。如果 t1t1 为晚上(例如22点以后),则将 t2t2t3t3 小于2点的情况视为次日的时间,加24小时处理。

2. 时间比较

在处理过跨日的时间后,直接比较 t3t3 是否晚于 t2t2,若是则超时,否则未超时。

代码实现

Python代码

def solution(t1: str, t2: str, t3: str) -> str:
    """
    判断时间 t2 和 t3 是否符合特定顺序:
    如果 t2 >= t3,返回 "No";否则返回 "Yes"。
    特殊情况下,将时间 00:xx - 02:xx 视为次日时间。
    """
    # 解析时间 t2 和 t3
    t1_hours, t1_minutes = map(int, t1.split(":"))
    t2_hours, t2_minutes = map(int, t2.split(":"))
    t3_hours, t3_minutes = map(int, t3.split(":"))

    if t1_hours >= 22:
        if t2_hours <= 2:
            t2_hours += 24
        if t3_hours <= 2:
            t3_hours += 24

    # 比较 t2 和 t3
    if t2_hours > t3_hours:
        return "No"
    elif t2_hours == t3_hours and t2_minutes >= t3_minutes:
        return "No"
    
    return "Yes"


if __name__ == "__main__":
    # 测试用例
    print(solution("18:00", "19:05", "19:05") == "No")  # 应输出 True
    print(solution("23:00", "00:21", "00:23") == "Yes")  # 应输出 True
    print(solution("23:05", "00:05", "23:58") == "No")  # 应输出 True

Go语言代码

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func solution(t1, t2, t3 string) string {
	t1Str := strings.Split(t1, ":")
	t2Str := strings.Split(t2, ":")
	t3Str := strings.Split(t3, ":")
	t1o, _ := strconv.Atoi(t1Str[0])
	t2o, _ := strconv.Atoi(t2Str[0])
	t2m, _ := strconv.Atoi(t2Str[1])
	t3o, _ := strconv.Atoi(t3Str[0])
	t3m, _ := strconv.Atoi(t3Str[1])
	if t1o >= 22 {
		if t2o <= 2 {
			t2o += 24
		}
		if t3o <= 2 {
			t3o += 24
		}
	}
	if t2o > t3o {
		return "No"
	} else if t2o == t3o && t2m >= t3m {
		return "No"
	}
	return "Yes"
}

func main() {
	fmt.Println(solution("18:00", "19:05", "19:05") == "No")
	fmt.Println(solution("23:00", "00:21", "00:23") == "Yes")
	fmt.Println(solution("23:05", "00:05", "23:58") == "No")
}