# [LeetCode] 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 题目讲解汇总(持续更新中...)

posted @ 2017-04-15 22:43  Grandyang  阅读(...)  评论(...编辑  收藏