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
相关推荐
01_3 分钟前
力扣hot100 ——搜索二维矩阵 || m+n复杂度优化解法
算法·leetcode·矩阵
SylviaW086 分钟前
python-leetcode 35.二叉树的中序遍历
算法·leetcode·职场和发展
篮l球场7 分钟前
LeetCodehot 力扣热题100
算法·leetcode·职场和发展
pzx_00119 分钟前
【机器学习】K折交叉验证(K-Fold Cross-Validation)
人工智能·深度学习·算法·机器学习
BanLul20 分钟前
进程与线程 (三)——线程间通信
c语言·开发语言·算法
qy发大财41 分钟前
分发糖果(力扣135)
数据结构·算法·leetcode
haaaaaaarry1 小时前
【分治法】线性时间选择问题
数据结构·算法
CS创新实验室1 小时前
计算机考研之数据结构:P 问题和 NP 问题
数据结构·考研·算法
OTWOL2 小时前
【C++编程入门基础(一)】
c++·算法
谏君之2 小时前
C语言实现的常见算法示例
c语言·算法·排序算法