高级编程技术第八次作业

670Maximum Swap

Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.

Example 1:

Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

Input: 9973
Output: 9973
Explanation: No swap.

Note:

  1. The given number is in the range [0, 108]

解题思路:

这道题是要找出一个数字经过一次交换最大能变成多少。我有两种思路,第一个是递归的方法:在每位都找一次对应该位数字的最大值,如果找到的最大值与该位不同,则交换后返回,如果相同则继续递归下一位去寻找后面的可以通过交换来变大的数字,代码如下。

class Solution(object):
    def maximumSwap(self, num):
        """
        :type num: int
        :rtype: int
        """
        ns=list(str(num))
        if len(ns)==1:
                return int(num)
        tmp='0'
        cou=0
        ma=0
        mi=0
        while cou<len(ns):
                if ns[cou]>=tmp:
                        ma=cou
                        tmp=ns[cou]
                cou+=1
        if ns[0]==tmp:
                ttt=ns[0]
                ns.remove(ns[0])
                ans=''
                for i in ns:
                        ans=ans+i
                return int(ttt)*pow(10,len(ns))+self.maximumSwap(ans)
        else:
                ns[ma]=ns[0]
                ns[0]=tmp
                ans=0
                for i in ns:
                        ans=ans*10+int(i)
                return ans

该代码通过了leetcode上的检验。

第二种方法就是非递归的方法,通过先对原数字转换而来的列表进行由大到小排序,找出原列表与排序后的列表第一个不同的index,记录这里应该被换为哪个才是最大的,然后在该位后面的数字寻找这个最大的数字,找到了则进行交换,需要注意的是这后面的数字应该越大越好,这样才能满足最大数字的要求,代码如下:

class Solution(object):
    def maximumSwap(self, num):
        """
        :type num: int
        :rtype: int
        """
        ns=list(str(num))
        nss=sorted(ns)
        nss.reverse()
        cou=0
        fir=0
        sec=0
        tmp=-1
        while cou<len(ns):
                if ns[cou]!=nss[cou]:
                        fir=cou
                        tmp=nss[cou]
                        break
                cou+=1
        if tmp==-1:
                return num
        cou+=1
        while cou<len(ns):
                if ns[cou]==tmp:
                        sec=cou
                cou+=1
        ns[sec]=ns[fir]
        ns[fir]=tmp
        ans=0
        for i in ns:
                ans=ans*10+int(i)
        return ans
该代码同样通过了leetcode的检验。

猜你喜欢

转载自blog.csdn.net/liangjan/article/details/80214902