题目:
给你一个正整数 n ,请你找出符合条件的最小整数,其由重新排列 n 中存在的每位数字组成,并且其值大于 n 。如果不存在这样的正整数,则返回 -1 。
注意 ,返回的整数应当是一个 32 位整数 ,如果存在满足题意的答案,但不是 32 位整数 ,同样返回 -1 。
示例 1:
输入:n = 12
输出:21
示例 2:
输入:n = 21
输出:-1
提示:
1 <= n <= 231 - 1
代码:
class Solution {
public:
int nextGreaterElement(int n) {
string num=to_string(n);
int len=num.length();
int j=len-1;
string temp="";
temp.push_back(num[j]);
while(j>=1){
if(num[j]<=num[j-1]){
temp.push_back(num[j-1]);
}else{
int olds=atoi(num.substr(j-1).c_str());
temp.insert(temp.begin(),num[j-1]);
for(int i=1;i<temp.length();i++){
if(temp[i]>temp[0]){
char t=temp[0];
temp[0]=temp[i];
temp[i]=t;
break;
}
}
int news=atoi(temp.c_str());
string res=num.substr(0,j-1)+temp;
return atoi(res.c_str())<n?-1:atoi(res.c_str());
}
j--;
}
return -1;}
};
想法:
需要找出其中的规律,最小整数,肯定是优先在后面的位发生变化,从后面向前面遍历,保持一个优先权队列,小的在前面,大的在后面,遇到不能一直递增的就停下,这个时候开始改变数字,把大于该数字的最小的数与在那个需要换的数字进行交换,其他数字保持递增的状态,这样就得到了符合条件的最小整数。需要注意的是如果交换以后溢出,那么一定交换后的数字比交换前的小,如果while循环遍历结束还没有找到需要交换的,那么说明数组从头到尾递减;在这两种情况下,应该返回-1;