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.
这是一道全排列的问题,直接用next_permutation()函数去做就可以了。注意long long 防止溢出
代码如下:
class Solution {
public:
int nextGreaterElement(int n) {
string s=to_string(n);
next_permutation(s.begin(),s.end());
long long re=stoll(s);
return (re>INT_MAX||re<=n)?-1:re;
}
};