# 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
``````

``````class Solution {
public:
int nextGreaterElement(int n) {
string str = to_string(n);
int len = str.size(), i = len - 1;
for (; i > 0; --i) {
if (str[i] > str[i - 1]) break;
}
if (i == 0) return -1;
for (int j = len - 1; j >= i; --j) {
if (str[j] > str[i - 1]) {
swap(str[j], str[i - 1]);
break;
}
}
sort(str.begin() + i, str.end());
long long res = stoll(str);
return res > INT_MAX ? -1 : res;
}
};
``````

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

Next Greater Element II

https://discuss.leetcode.com/topic/85740/c-4-lines-next_permutation

https://discuss.leetcode.com/topic/86049/simple-java-solution-4ms-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation