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 ansJava实现
class Solution { public int findMinDifference(ListtimePoints) { 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'); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)