下一个更大的元素 III

本文介绍了一个算法问题,即如何找到比给定32位整数大的下一个排列的最小整数。通过字符串转换和排列算法,文章详细解释了实现这一目标的具体步骤,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个32位整数n,用同样的数字组成新的32位整数,使得它要比n大,返回最小的这样的数。如果不存在这样的整数,返回-1。

样例

样例 1:

输入: 12
输出: 21

样例 2:

输入: 21
输出: -1

 

class Solution {
public:
    /**
     * @param n: an integer
     * @return: the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n
     */
    int nextGreaterElement(int n) 
    {
    
        // Write your code here
        string tmp = std::to_string(n);
        string ret = nextPermutation(tmp);
        long num = stol(ret);
        if(num == n || num > INT_MAX)
            return -1;
        return num;
    }
    
    
    string nextPermutation(string &nums) 
    {
        // write your code here
        int size = nums.size();
        if(size == 1)
            return nums;
        int i = 0;
        int j = -1;
        int k = -1;
        for(i=size-1; i>=0; i--)
        {
            if(nums[i]>nums[i-1] && i >= 1)
            {
                j=i-1;
                break;
            }
        }
        if( j == -1)
        {
            
            return nums;
        }
            
        
        for(i=size-1; i>=0; i--)
        {
            if(nums[i] > nums[j])
            {
                k=i;
                break;
            }
        }
        
        int tmp = nums[j];
        nums[j]  = nums[k];
        nums[k] = tmp;
        

        sort(nums.begin()+j+1, nums.end());
        return nums;
        
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值