[英]Optimization for next greater number with same set of digits from code wars
任務是找到具有相同數字的下一個更大的數字。
所以,這里有一些示例:
Input: n = "218765"
Output: "251678"
Input: n = "1234"
Output: "1243"
Input: n = "4321"
Output: "Not Possible"
Input: n = "534976"
Output: "536479"
樣本取自極客的極客
def next_bigger(n):
if len(str(n)) == 1:
return -1
else:
pass
k = math.factorial(len(str(n)))
lst2 = []
lst3 = []
lst4 = []
for num in str(n):
lst2.append(num)
for num in lst2:
if lst2.count(num) == len(lst2):
return -1
else:
pass
for num in lst2:
if lst2.count(num) > 1 and num not in lst4:
k = k/math.factorial(lst2.count(num))
lst4.append(num)
else:
pass
while True:
shuffle(lst2)
if int(''.join(lst2)) not in lst3:
lst3.append(int(''.join(lst2)))
print(len(lst3))
pass
if int(''.join(lst2)) in lst3:
if len(lst3) == k:
break
else:
pass
t = sorted(lst3)
for num in t:
if num > n:
return num
else:
pass
return -1
我的代碼似乎可以工作,但它會超時。 首先,代碼檢查角解,例如n = 1111
或n = 3
其次,它使用組合來確定可以從給定數字中獲得多少組合。 第三,它會隨機排列數字以獲取所有可用的組合並將它們添加到列表中。 從那里它只是從給定的數字中獲取下一個數字或返回-1。
它似乎適用於所有樣本。
是否有可能以某種方式優化這種解決這個問題的方式?
使用 Python 一切皆有可能:)
你可以做這樣的事情
def next_greater_number(n):
n_s = str(n)
N = len(n_s)
min_digit = int(n_s[-1])
min_digit_idx = N-1
left_side = n_s
right_side = ''
for i in range(len(n_s)-1, 0, -1):
left_side = left_side[:i]
right_side = n_s[i] + right_side
# print(left_side, right_side)
# keep record of minimum number
if int(n_s[i]) < min_digit:
min_digit_idx = i
min_digit = int(n_s[i])
# get to the point where right digit is greater than left digit
if int(n_s[i]) > int(n_s[i-1]):
# exclude min digit, because we will append it on the left side
right_side = n_s[i:min_digit_idx] + n_s[min_digit_idx+1:] + left_side[-1]
right_side = ''.join(sorted(right_side))
output = left_side[:-1] + str(min_digit) + right_side
break
else:
output = "Not Possible"
return output
通過從右到左遍歷尋找右側數字大於左側數字的模式。 我們需要用左側最后一位數字替換右側的最小值。 之后,右側的排序使數字剛好大於當前數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.