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
相关推荐
计信金边罗31 分钟前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
MZWeiei36 分钟前
KMP 算法中 next 数组的构建函数 get_next
算法·kmp
Fanxt_Ja2 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
luofeiju2 小时前
行列式的性质
线性代数·算法·矩阵
緈福的街口2 小时前
【leetcode】347. 前k个高频元素
算法·leetcode·职场和发展
半桔3 小时前
【Linux手册】冯诺依曼体系结构
linux·缓存·职场和发展·系统架构
pen-ai3 小时前
【统计方法】基础分类器: logistic, knn, svm, lda
算法·机器学习·支持向量机
鑫鑫向栄3 小时前
[蓝桥杯]春晚魔术【算法赛】
算法·职场和发展·蓝桥杯
roman_日积跬步-终至千里3 小时前
【Go语言基础【3】】变量、常量、值类型与引用类型
开发语言·算法·golang
FrankHuang8884 小时前
使用高斯朴素贝叶斯算法对鸢尾花数据集进行分类
算法·机器学习·ai·分类