首先将整数转换为数字列表。随后,分别提取出奇数和偶数位的数字,并对它们进行降序排序。在构建最终结果时,遍历原始数字列表,根据每个数字的奇偶性,从排序后的奇数或偶数列表中取出当前最大值进行替换。这种方式确保了每个位置上的数字是可能的最大值,从而使得整个数字尽可能大。
时间复杂度: O(n log n)
空间复杂度: O(n)
class Solution:
def largestInteger(self, num: int) -> int:
# Convert the input number to a list of digits
digits = list(str(num))
# Separate the odd and even digits
odd_digits = [int(d) for d in digits if int(d) % 2 != 0]
even_digits = [int(d) for d in digits if int(d) % 2 == 0]
# Sort the odd and even digits in descending order
odd_digits.sort(reverse=True)
even_digits.sort(reverse=True)
# Create a result list to store the rearranged digits
result = []
# Iterate over the original digits and replace them with the largest possible digit
# of the same oddity (odd or even)
for d in digits:
digit = int(d)
if digit % 2 != 0:
# Replace the current odd digit with the largest odd digit
result.append(str(odd_digits.pop(0)))
else:
# Replace the current even digit with the largest even digit
result.append(str(even_digits.pop(0)))
# Join the result list into a string and convert it back to an integer
return int(''.join(result))
solution = Solution()
num = 1234
max_num = solution.largestInteger(num)
print(max_num) # Output: 3412