這道題爲中等題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