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
相关推荐
地平线开发者29 分钟前
征程6工具链模型X86推理方式说明
算法
地平线开发者33 分钟前
【征程6】校准量化中HistogramObserver解析
算法
OuO-21 小时前
笔试强训 Day 34:ISBN 号码、kotori 和迷宫、矩阵最长递增路径
java·算法·矩阵
程序喵大人2 小时前
【C++进阶】STL算法与函数对象 - 04 find、count和any_of把查询写成意图
开发语言·c++·算法
豆沙沙包?2 小时前
c++中引用(P7-P11)
java·c++·算法
不会代码的小猴3 小时前
标准模板库(STL)
开发语言·c++·笔记·算法
ZhouDevin3 小时前
算法论文/高效微调4——DoRA:权重分解的低秩适配方法
算法
evans在进步3 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先
AI探索先锋3 小时前
A* 路径规划:四种算法的进化史-学习
学习·算法
旖旎夜光3 小时前
LeetCode 202:快乐数(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针