LeetCode 539. 最小时间差(C++、python)

给定一个 24 小时制(小时:分钟)的时间列表,找出列表中任意两个时间的最小时间差并已分钟数表示。


示例 1:

输入: ["23:59","00:00"]
输出: 1


备注:

列表中时间数在 2~20000 之间。

每个时间取值在 00:00~23:59 之间。

C++

class Solution {
public:
    static bool compare(string& a, string& b)
    {
        if(a.substr(0,2)==b.substr(0,2))
        {
            return a.substr(3,2) < b.substr(3,2);
        }
        else
        {
            return a.substr(0,2) < b.substr(0,2);
        }
    }
    
    int findMinDifference(vector<string>& timePoints) 
    {
        int n=timePoints.size();
        sort(timePoints.begin(), timePoints.end(), compare);
        int res=INT_MAX;
        for(int i=1;i<n;i++)
        {
            int tmp=(stoi(timePoints[i].substr(0,2))-stoi(timePoints[i-1].substr(0,2)))*60+stoi(timePoints[i].substr(3,2))-stoi(timePoints[i-1].substr(3,2));
            if(tmp<res)
            {
                res=tmp;
            }
        }
        int tmp=(stoi(timePoints[0].substr(0,2))-stoi(timePoints[n-1].substr(0,2))+24)*60+stoi(timePoints[0].substr(3,2))-stoi(timePoints[n-1].substr(3,2));
        return min(res,tmp);       
    }
};

python

class Solution:
    def findMinDifference(self, timePoints: 'List[str]') -> 'int':
        n=len(timePoints)
        res=[]
        for i in range(n):
            res.append(int(timePoints[i][0:2])*60+int(timePoints[i][3:5]))
        res.sort()
        tmp=res[0]+24*60-res[n-1]
        for i in range(1,n):
            tmp=min(tmp,res[i]-res[i-1])
        return tmp
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值