leetcode - 556. Next Greater Element III

Description

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

Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.

Example 1:

复制代码
Input: n = 12
Output: 21

Example 2:

复制代码
Input: n = 21
Output: -1

Constraints:

复制代码
1 <= n <= 2^31 - 1

Solution

Solved after help...

Same as 31. 下一个排列

The next greater number should be: start from the rightmost, and until we find a digit that is smaller than at least one of the digits we have visited, we should swap the digit with the minimum but larger digit of all the digits we have visited. Then sort all the digits at the right. Then we would get our answer.

Time complexity: o ( n log ⁡ n ) o(n\log n) o(nlogn)

Space complexity: o ( n ) o(n) o(n)

Code

python3 复制代码
class Solution:
    def nextGreaterElement(self, n: int) -> int:
        num_list = []
        while n > 0:
            num_list.append(n % 10)
            n //= 10
        stack = []
        for i in range(len(num_list)):
            if not stack or num_list[stack[-1]] <= num_list[i]:
                stack.append(i)
            else:
                swap_index = stack[-1]
                # swap current number with previous minimum larger one
                while stack and num_list[stack[-1]] > num_list[i]:
                    swap_index = stack.pop()
                num_list[i], num_list[swap_index] = num_list[swap_index], num_list[i]
                num_list[:i] = sorted(num_list[:i], reverse=True)
                i = len(num_list) + 1
                break
        if i == len(num_list) + 1:
            res = eval(''.join(map(str, num_list[::-1])))
            if res > 2 ** 31 - 1:
                res = -1
        else:
            res = -1
        return res
相关推荐
cccc来财22 分钟前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode
Coovally AI模型快速验证1 小时前
数据集分享 | 智慧农业实战数据集精选
人工智能·算法·目标检测·机器学习·计算机视觉·目标跟踪·无人机
墨尘游子1 小时前
目标导向的强化学习:问题定义与 HER 算法详解—强化学习(19)
人工智能·python·算法
恣艺2 小时前
LeetCode 854:相似度为 K 的字符串
android·算法·leetcode
予早2 小时前
《代码随想录》刷题记录
算法
满分观察网友z2 小时前
别总想着排序!我在数据看板中悟出的O(N)求第三大数神技(414. 第三大的数)
算法
满分观察网友z2 小时前
别只知道暴力循环!我从用户名校验功能中领悟到的高效字符集判断法(1684. 统计一致字符串的数目)
算法
刚入坑的新人编程2 小时前
暑期算法训练.9
数据结构·c++·算法·leetcode·面试·排序算法
码事漫谈3 小时前
AGI就像暴雨,可能说来就来
算法
workflower3 小时前
数据分析前景
算法·数据挖掘·数据分析·需求分析·软件需求