556.Next Greater Element III
1-找逆序,排序
https://leetcode.com/problems/next-greater-element-iii/discuss/101824/
class Solution {
public int nextGreaterElement(int n) {
char[] number = (n + "").toCharArray();
int i;
for(i = number.length - 1; i > 0; i--){
if(number[i - 1] < number[i])
break;
}
//if the number is the largest
if(i == 0)
return -1;
int swapedVal = number[i - 1];
int smallestValInRight = number[i];
int smallestValPosInRight = i;
for(int j = i + 1; j < number.length; j++){
if(number[j] > swapedVal && number[j] < smallestValInRight){
smallestValInRight = number[j];
smallestValPosInRight = j;
}
}
char tmp = number[i - 1];
number[i - 1] = number[smallestValPosInRight];
number[smallestValPosInRight] = tmp;
Arrays.sort(number, i, number.length);
long val = Long.parseLong(new String(number));
return (val <= Integer.MAX_VALUE) ? (int) val: -1;
}
}