Leetcode-556. 下一个更大元素 III -python

题目

给定一个32位正整数 n,你需要找到最小的32位整数,其与 n 中存在的位数完全相同,并且其值大于n。如果不存在这样的32位整数,则返回-1。
链接:https://leetcode-cn.com/problems/next-greater-element-iii/

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:

Input: 230241
Output: 230412

思路及代码

  • 找到第一位开始降序的位置:比如230241-从末位1开始14是升序,到2就降序了
  • reverse这一位之后的所有,得到230214
  • 交换这一位与这一位之后第一个大于他的数字,即交换2和4得到230412
class Solution:
    def nextGreaterElement(self, n: int) -> int:
        s = list(map(int,str(n)))
        i = len(s) - 1
        # 找到第一位开始降序的位置:如230241中的4的位置
        while i >= 1 and s[i] <= s[i-1]:
            i -= 1
        if i == 0:
            return -1
        s[i:len(s)] = reversed(s[i:len(s)])
        for j in range(i,len(s)):
            if s[j] > s[i-1]:
                break
        s[i-1], s[j] = s[j], s[i-1]
        ans = int("".join(map(str,s)))
        if ans > 2**31-1: # (1<<31)-1
            return -1
        return ans

你可能感兴趣的:(Leetcode,leetcode,python,算法)