My solution in Python


  • 0
    G
    class Solution(object):
        def maximumSwap(self, num):
            """
            :type num: int
            :rtype: int
            """
            nums = list(str(num))
            sortedNums = list(sorted(nums, reverse = True))
            for i in range(len(sortedNums) - 1):
                if nums[i] != sortedNums[i]:
                    for j in range(len(nums) - i - 1):
                        if nums[len(nums) - j - 1] == sortedNums[i]:
                            idx = len(nums) - j - 1
                            break
                    nums[i], nums[idx] = nums[idx], nums[i]
                    return int(''.join(nums))
            return num
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.