556. Next Greater Element III

该博客介绍了如何解决一个算法问题,即给定一个正整数n,找到数字相同的且大于n的最小整数。通过将数字n转换为字符串,然后应用类似于排列的逻辑,找到第一个逆序对并进行调整,再对剩余部分进行排序。如果结果超出了32位整数范围,则返回-1。示例中给出了12到21和21到-1的转换过程。代码实现使用了C++,时间复杂度和空间复杂度均为O(1)。
摘要由CSDN通过智能技术生成

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 <= 231 - 1

题目:给定一个正整数n,找下一个比它大的整数,要求其中包含的数字不变。

思路:与31.Next Permutaion思路一样。可以将整数n转换成vector<int>型,也可以用字符串型。这里为了偷懒,用字符串型。代码:

class Solution {
public:
    int nextGreaterElement(int n) {
        string s = to_string(n);
        int i = s.length()-1;
        while(i > 0 && s[i] <= s[i-1]) i--;
        i--;
        if(i < 0) return -1;
        int i1 = i+1;
        while(i1 < s.length() && s[i1] > s[i]) i1++;
        i1--;
        swap(s[i], s[i1]);
        sort(s.begin()+i+1, s.end());
        string intmax = to_string(INT_MAX);
        if(s.length() == intmax.length() && s > intmax) return -1;
        return stoi(s);
    }
};

time: O(1), space: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值