力扣每日一题2022-01-18中等题:最小时间差

力扣每日一题2022-01-18中等题:最小时间差,第1张

力扣每日一题2022-01-18中等题:最小时间差

最小时间差

539.最小时间差

题目描述思路

排序

Python实现Java实现


539.最小时间差 题目描述

最小时间差


思路 排序

对timePoints排序后,最小时间差必然出现在timePoints的两个相邻时间,或者timePoints的两个首尾时间中。因此排序后遍历timePoints即可得到最小时间差。

Python实现

class Solution:
    
    def getMinutes(self, t: str) -> int:
        return ((ord(t[0]) - ord('0')) * 10 + ord(t[1]) - ord('0')) * 60 + (ord(t[3]) - ord('0')) * 10 + ord(t[4]) - ord('0')
    
    
    def findMinDifference(self, timePoints: List[str]) -> int:
        timePoints.sort()
        ans = float('inf')
        t0Minutes = self.getMinutes(timePoints[0])
        preMinutes = t0Minutes
        for i in range(1, len(timePoints)):
            minutes = self.getMinutes(timePoints[i])
            ans = min(ans, minutes-preMinutes)
            preMinutes = minutes
        ans = min(ans, t0Minutes + 1440 - preMinutes)
        return ans

Java实现

class Solution {
    public int findMinDifference(List timePoints) {
        Collections.sort(timePoints);
        int ans = Integer.MAX_VALUE;
        int t0Minutes = getMinutes(timePoints.get(0));
        int preMinutes = t0Minutes;
        for (int i = 1; i < timePoints.size(); ++i) {
            int minutes = getMinutes(timePoints.get(i));
            ans = Math.min(ans, minutes - preMinutes);
            preMinutes = minutes;
        }
        ans = Math.min(ans, t0Minutes + 1440 - preMinutes);
        return ans;
    }
    
    public int getMinutes(String t) {
        return ((t.charAt(0) - '0') * 10 + (t.charAt(1) - '0')) * 60 + (t.charAt(3) - '0') * 10 + (t.charAt(4) - '0');
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5707545.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存