Given a positive integer n
, find the smallest integer which has exactly the same digits existing in the integer n
and is greater in value than n
. If no such positive integer exists, return -1
.
Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1
.
Example 1:
Input: n = 12 Output: 21
Example 2:
Input: n = 21 Output: -1
Constraints:
1 <= n <= 231 - 1
题目:给定一个正整数n,找下一个比它大的整数,要求其中包含的数字不变。
思路:与31.Next Permutaion思路一样。可以将整数n转换成vector<int>型,也可以用字符串型。这里为了偷懒,用字符串型。代码:
class Solution {
public:
int nextGreaterElement(int n) {
string s = to_string(n);
int i = s.length()-1;
while(i > 0 && s[i] <= s[i-1]) i--;
i--;
if(i < 0) return -1;
int i1 = i+1;
while(i1 < s.length() && s[i1] > s[i]) i1++;
i1--;
swap(s[i], s[i1]);
sort(s.begin()+i+1, s.end());
string intmax = to_string(INT_MAX);
if(s.length() == intmax.length() && s > intmax) return -1;
return stoi(s);
}
};
time: O(1), space: O(1)