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
这道题是找相同数字集按大小顺序组合出的下一个数字,题目难度为Medium。
题目和第31题是完全一样的,感兴趣的同学可以顺便看下第31题(传送门)。
如果从数字的第k位开始到数字尾部都是递减的并且第k位数字比第k-1位数字大,表明从第k位开始到尾部的这段数字是他们能组合出的最大数字,在下一个数字中他们要整体倒序变为能组合出的最小数字,倒序后从这段数字序列中找出第一个大于第k-1位数字的位置和第k-1位交换即可。举个栗子,如果n=13452,其中52是递减的,而且5>4,这样我们先把52倒序,n就变为13425,然后从25中找出第一个大于4的数字和4交换,就得到了最终结果13524。需要注意的是下一个数字可能会超出INT_MAX范围。具体代码:
class Solution { public: int nextGreaterElement(int n) { string num = to_string(n); int i = num.size()-1; while(i && num[i]<=num[i-1]) --i; if(!i) return -1; reverse(num.begin()+i, num.end()); for(int j=i; j<num.size(); ++j) { if(num[j] > num[i-1]) { swap(num[j], num[i-1]); break; } } if(num.size() == 10 && num > to_string(INT_MAX)) return -1; return stoi(num); } };