Description
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
Analysis
此处要利用next_permutation函数,其函数原型为:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
当前序列不存在下一个排列时,函数返回false,否则返回true。
Code
class Solution {
public:
int nextGreaterElement(int n) {
string s = to_string(n);
next_permutation(begin(s),end(s));
long result = stol(s);
return (result > INT_MAX || result <= n)? -1 : result;
}
};
Appendix
- Link: https://leetcode.com/problems/next-greater-element-iii/
- Run Time: 0ms