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 <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
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;
}
};