leetcode 556. Next Greater Element III 下一个字典序

Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.

Example 1:
Input: 12
Output: 21
Example 2:
Input: 21
Output: -1

本题题意很简单,直接寻找字典序的下一个位置即可

和leetcode 503. Next Greater Element II 不太一样

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;


class Solution
{
public:
    int nextGreaterElement(int n)
    {
        string s = to_string(n);
        next_permutation(s.begin(), s.end());
        long long res = stoll(s);
        return (res > INT_MAX || res <= n) ? -1 : (int)res;
    }
};

你可能感兴趣的:(leetcode,For,Java,需要好好想一下的题目,leetcode,For,C++)