【每日一题0813】相同数字的最近整数

:woman_mage:给定一个正整数,请编写一个python函数,返回最近一个较小的,由原来的所有数字组成的正整数。如果没有合适的结果请返回-1

示例:
输入:21 ,输出:12
输入:2021 ,输出:2012
输入:9 ,输出:-1

题目难度:困难
题目来源:codewars

def next_smaller(num: int) -> int:
    pass
  
assert next_smaller(21) == 12
assert next_smaller(2021) == 2012
assert next_smaller(9) == -1
assert next_smaller(135) == -1
from itertools import permutations


def next_smaller(num):
    pernum = [int(''.join(x)) for x in list(permutations(str(num))) if x[0]!='0' ]
    temp = [i - num for i in pernum]
    # 获取最大负数 和最小正数
    max_temp = max([n for n in temp if n < 0] if [n for n in temp if n < 0] else [0])
    min_temp = min([n for n in temp if n > 0] if [n for n in temp if n > 0] else [0])
    result = pernum[temp.index(min(max_temp, min_temp))]
    return -1 if result == num else result


assert next_smaller(21) == 12
assert next_smaller(2021) == 2012
assert next_smaller(9) == -1
assert next_smaller(135) == -1
def next_smaller(num: int) -> int:
    
    s = str(num)
    
    if ''.join(sorted(s)) == s or len(s) == 1:
        return -1
    
    nums = [int(''.join(x)) for x in list(permutations(s))]
    result = max([x for x in nums if x < int(s)])
    
    return result

assert next_smaller(21) == 12
assert next_smaller(2021) == 2012
assert next_smaller(9) == -1
assert next_smaller(135) == -1

解题思路:使用排列将所有可能的组合列举出来,然后比较。
缺点:如果数字位数比较多,耗时较长,性能较差。

关闭