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
相关推荐
木头左2 小时前
自适应门限动态调整算法在量化交易策略中的应用
算法
deepdata_cn2 小时前
非线性规划(NLP)算法
算法
TL滕2 小时前
从0开始学算法——第十五天(滑动窗口)
笔记·学习·算法
@小码农2 小时前
2025年全国青少年信息素养大赛 Gandi编程 小低组初赛真题
数据结构·人工智能·算法·蓝桥杯
CoderYanger2 小时前
贪心算法:7.最长连续递增序列
java·算法·leetcode·贪心算法·1024程序员节
鹿角片ljp2 小时前
力扣104.求二叉树最大深度:递归和迭代
算法·leetcode·二叉树·递归
天天进步20152 小时前
Linux 实战:如何像查看文件一样“实时监控” System V 共享内存?
开发语言·c++·算法
菜鸟‍2 小时前
【论文学习】Co-Seg:互提示引导的组织与细胞核分割协同学习
人工智能·学习·算法
我是你们的明哥3 小时前
Java优先级队列(PriorityQueue)详解:原理、用法与实战示例
后端·算法
仰泳的熊猫3 小时前
1176 The Closest Fibonacci Number
数据结构·c++·算法·pat考试