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
相关推荐
重庆小透明41 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq1 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
clock的时钟2 小时前
暑期数据结构第一天
数据结构·算法
小小小小王王王2 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
BIYing_Aurora2 小时前
【IPMV】图像处理与机器视觉:Lec13 Robust Estimation with RANSAC
图像处理·人工智能·算法·计算机视觉
martian6654 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习4 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
??tobenewyorker5 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
让我们一起加油好吗5 小时前
【基础算法】贪心 (二) :推公式
数据结构·数学·算法·贪心算法·洛谷