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

给定32位正整数n,寻找位数相同且值大于n的最小32位整数。例如,输入230241,输出230412。思路是从末位开始找到第一个降序位置,反转该位置后的数字并交换此位置与其后首个大于它的数字。

题目

给定一个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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值