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
思路:
1、从后往前找,找到第一个相邻的逆序对num[i] < num[i+1]
2、从后往前找,找到第一个大于num[i]的数,num[j]
3、交换num[i]和num[j]两个数
4、将i+1~num.length-1之间的数反转
上述方法同样可以用来求所有数字的排列组合。
程序如下所示;
class Solution {
public int nextGreaterElement(int n) {
String s = String.valueOf(n);
char[] ch = s.toCharArray();
if (ch.length <= 1){
return -1;
}
int i = 0;
for (i = ch.length - 2; i >= 0; -- i){
if (ch[i+1] > ch[i]){
break;
}
}
if (i == -1){
return -1;
}
int j = ch.length - 1;
while (ch[j] <= ch[i]) {
j --;
}
char tmp = ch[i];
ch[i] = ch[j];
ch[j] = tmp;
int l = i + 1, r = ch.length - 1;
while (l < r){
tmp = ch[l];
ch[l++] = ch[r];
ch[r--] = tmp;
}
long res = Long.parseLong(new String(ch));
return (res > Integer.MAX_VALUE)?-1:(int)res;
}
}