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
相关推荐
小白的高手之路14 小时前
【LeetCode 热题 100】560. 和为 K 的子数组|前缀和、哈希表(Python)
数据结构·笔记·python·算法·leetcode·力扣·散列表
专注仿真14 小时前
仿真智能体训练(评估篇):鲁棒性/泛化测试算法详解与实战
人工智能·python·算法·afsim智能体训练·评估算法·鲁棒性算法·泛化测试算法
纪念 22914 小时前
C++ 算法模板与错题 模拟(一)
android·c++·算法
电科_银尘14 小时前
【大模型算法与工程 51】检索基础:Embedding、向量索引与BM25
算法·机器学习·embedding
空堂与归15 小时前
2026-12-02_Anthropic格密码银河级算法
人工智能·算法·ai·密码学
蓝色汪洋15 小时前
qsort使用指南
数据结构·算法
大熊背15 小时前
海思 ISP 光圈控制(AI / DC-Iris / P-Iris)详解
算法·自动曝光·曝光路径
weixin_3077791316 小时前
Python用正则把 SQL 关键字整词匹配后转成小写
开发语言·python·sql·算法
Code_Solitude17 小时前
c语言:期末复习5(二维数组)
c语言·数据结构·算法
CV爱数码17 小时前
论文精读|DC-PnPDP(ICML 2026):给即插即用扩散先验加回 ADMM 的对偶变量
人工智能·深度学习·算法·3d·ct