美文网首页Leetcode
Leetcode 670. Maximum Swap

Leetcode 670. Maximum Swap

作者: SnailTyan | 来源:发表于2021-02-03 14:08 被阅读0次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Maximum Swap

    2. Solution

    • Version 1
    class Solution:
        def maximumSwap(self, num):
            s = list(str(num))
            length = len(s)
            if length < 2:
                return num
    
            for i in range(length - 1):
                max_index = i
                for j in range(i + 1, length):
                    if s[j] >= s[max_index] and s[i] != s[j]:
                        max_index = j
                if max_index != i:
                    temp = s[i]
                    s[i] = s[max_index]
                    s[max_index] = temp
                    break 
    
            return int(''.join(s))
    
    • Version 2
    class Solution:
        def maximumSwap(self, num):
            s = list(str(num))
            length = len(s)
            if length < 2:
                return num
    
            pre = 0
            post = 0
            max_index = length - 1
            for i in range(length - 1, -1, -1):
                if s[i] > s[max_index]:
                    max_index = i
                elif s[i] < s[max_index]:
                    pre = i
                    post = max_index
    
    
            temp = s[pre]
            s[pre] = s[post]
            s[post] = temp
            
    
            return int(''.join(s))
    

    Reference

    1. https://leetcode.com/problems/maximum-swap/

    相关文章

      网友评论

        本文标题:Leetcode 670. Maximum Swap

        本文链接:https://www.haomeiwen.com/subject/xxnytltx.html