Python straightforward solution


  • 1
    A
    class Solution:
        def maximumSwap(self, num):
            """
            :type num: int
            :rtype: int
            """
            from collections import defaultdict
            num = list(map(int, str(num)))
            mydict = defaultdict(list)
            for i, x in enumerate(num):
                mydict[x].append(i)
            for i, x in enumerate(num):
                for max_val in range(9, x-1, -1):
                    if max_val in mydict:
                        break
                if x == max_val:
                    mydict[x].remove(mydict[x][0])
                    if len(mydict[x]) == 0:
                        del mydict[x]
                else:
                    idx = mydict[max_val].pop()
                    num[i], num[idx] = num[idx], num[i]
                    break
            return int(''.join(map(str, num)))
    

Log in to reply
 

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