LeetCode---556. Next Greater Element III

题目

给出一个32bit的正整数n,你需要找到一个这样的数,这个数和原来的数含有相同的数字,但是新数是比原数大的最小的数。如果不存在就返回-1。如:

Example 1:

Input: 12
Output: 21

Example 2:

Input: 21
Output: -1

Python题解

class Solution:
    def nextGreaterElement(self, n):
        """
        :type n: int
        :rtype: int
        """
        nums = list(map(int, str(n)))
        i = len(nums) - 2
        while i >= 0 and nums[i + 1] <= nums[i]:
            i -= 1
        if i == -1:
            return -1
        j = len(nums) - 1
        while j >= 0 and nums[j] <= nums[i]:
            j -= 1
        nums[i], nums[j] = nums[j], nums[i]

        self.reverse(nums, i + 1)

        res = int(''.join(map(str, nums)))
        return res if res <= (1 << 31) -1 else -1

    def reverse(self, nums, start):
        i, j = start, len(nums) - 1
        while i < j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值