[leetcode] 556. Next Greater Element III @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88835782

原题

Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

解法

从右到左找到第一个降序的数字, index记为i-1, 然后从右到左找到第一个比这个数字大的数字, index记为j, 交换两个数字的值, 然后将i-1之后的序列倒序排列即可. 当降序的数字不存在时, i==0, 返回-1. 当得到的结果超过32-bit时, 也返回-1.

代码

class Solution(object):
    def nextGreaterElement(self, n):
        """
        :type n: int
        :rtype: int
        """
        s = list(str(n))
        i = len(s)-1
        
        # find the first index that decrease from right        
        while i-1 >=0 and s[i-1] >= s[i]:
            i -= 1
            
        if i == 0: return -1        
        # find the first index that is bigger than s[i-1]
        j = len(s)-1
        while s[j] <= s[i-1]:
            j -= 1            
        # swap the values
        s[i-1], s[j] = s[j], s[i-1]        
        # reverse the list after i-1
        s[i:] = s[i:][::-1]
        res = int(''.join(s))        
        # check if res is 32-bit integer
        if res <= 2**31-1:
            return res
        return -1

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88835782
今日推荐