题解 | #下一个更大的数(三)#
下一个更大的数(三)
http://www.nowcoder.com/practice/475da0d4e37a481bacf9a09b5a059199
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
public int nextGreaterElement(int n) {
// write code here
String str = n + "";
char[] chrs = str.toCharArray();
for (int currentIndex = chrs.length - 1; currentIndex > 0; currentIndex--) {
if (chrs[currentIndex] > chrs[currentIndex - 1]) {
char previousValue = chrs[currentIndex - 1];
int swapIndex = currentIndex;
for (int tmpIndex = currentIndex + 1; tmpIndex < chrs.length; tmpIndex++) {
if (chrs[tmpIndex] > previousValue && chrs[tmpIndex] < chrs[swapIndex]) {
swapIndex = tmpIndex;
}
}
chrs[currentIndex - 1] = chrs[swapIndex];
chrs[swapIndex] = previousValue;
Arrays.sort(chrs, currentIndex, chrs.length);
break;
}
}
StringBuffer sb = new StringBuffer("");
for (char chr : chrs) {
sb.append(chr);
}
return Integer.valueOf(new String(sb)) == n ? -1 : Integer.valueOf(new String(sb));
}
}