这道题为中等题git
Given a time represented in the format "HH:MM", form the next closest time by reusing the current digits. There is no limit on how many times a digit can be reused.this
You may assume the given input string is always valid. For example, "01:34", "12:09" are all valid. "1:34", "12:9" are all invalid.spa
Example 1:code
Input: "19:34" Output: "19:39" Explanation: The next closest time choosing from digits 1, 9, 3, 4, is 19:39, which occurs 5 minutes later. It is not 19:33, because this occurs 23 hours and 59 minutes later.
Example 2:orm
Input: "23:59" Output: "22:22" Explanation: The next closest time choosing from digits 2, 3, 5, 9, is 22:22. It may be assumed that the r
个人思路: 这个题我首先把时间转换为字符串,而后循环获得c0,c1,c2,c3分别表示比当前位置数大的最小的一个数,首先比较最低位(好比上面第一个例子的4),若是有比他大的数那么就改变它的值再返回,而后再比较倒数第二位数,若是c1比他自己大且c1小于等于5,那么改变它的值并返回,同理再比较倒数第三个值,倒数第四个值,不然就所有返回最小值. 这个思路仍是比较清晰,可是有个缺点就是代码量太大了,若是遇见还有秒的话,就比较麻烦.blog
大神:保存现有集合,不断增长1分钟,当心,若是分钟超过59,增长小时,若是小时超过23,将小时重设为0,而后检查是否使用原始时间内的全部数字,以先到者为准.字符串
个人代码:input
1 class Solution(object): 2 def nextClosestTime(self, time): 3 """ 4 :type time: str 5 :rtype: str 6 """ 7 a = [int(i) for i in time if i != ':'] 8 b = min(min(a[0], a[1]), min(a[2], a[3])) 9 d = max(max(a[0], a[1]), max(a[2], a[3])) 10 c0 = d 11 c1 = d 12 c2 = d 13 c3 = d 14 15 for i in a: 16 if i > a[0]: c0 = min(c0, i) 17 if i > a[1]: c1 = min(c1, i) 18 if i > a[2]: c2 = min(c2, i) 19 if i > a[3]: c3 = min(c3, i) 20 if a[3] < c3: 21 a[3] = c3 22 elif a[2] < c2 and c2 <= 5: 23 a[2] = c2 24 a[3] = b 25 elif (a[1] < c1 and c1 <= 9 and a[0] <= 1) or (a[0] == 2 and a[1] < c1 and c1 <= 3): 26 a[1] = c1 27 a[2] = b 28 a[3] = b 29 elif a[0] < c0 and c0 <= 2: 30 a[0] = c0 31 a[1] = b 32 a[2] = b 33 a[3] = b 34 else: 35 a[0] = b 36 a[1] = b 37 a[2] = b 38 a[3] = b 39 a.insert(2,':') 40 return ''.join([str(i) for i in a])
大神代码:string
1 class Solution(object): 2 def nextClosestTime(self, time): 3 """ 4 :type time: str 5 :rtype: str 6 """ 7 hour,minute = time.split(':') 8 digits = set(map(int,[ digit for digit in hour + minute ])) 9 while True: 10 hour, minute = int(hour), int(minute) 11 hour, minute = (hour, minute + 1) if minute < 59 else ((hour + 1)%24, 0) 12 hour = str(hour) if 10 <= hour < 24 else '0' + str(hour) 13 minute = str(minute) if 10 <= minute < 60 else '0' + str(minute) 14 current = set(map(int,[ digit for digit in hour + minute ])) 15 if not (current - digits): # current is proper subset of digits 16 break 17 return hour + ':' + minute