0556. Next Greater Element III
Description
**Input:** n = 12
**Output:** 21**Input:** n = 21
**Output:** -1ac
class Solution {
public int nextGreaterElement(int n) {
// edge cases
if (n <= 10) return -1;
List<Integer> list = new ArrayList<>();
int exchange = -1;
while (n > 0) {
int curr = n % 10;
n /= 10;
if (list.size() != 0 && curr < list.get(list.size() - 1)) {
int i = list.size() - 1;
while (i >= 0 && curr < list.get(i)) i--;
exchange = list.get(i+1);
list.set(i+1, curr);
break;
} else {
list.add(curr);
}
}
if (n == 0 && exchange == -1) return -1; // cannot find result
n = n * 10 + exchange;
for (int i : list) {
if (n > Integer.MAX_VALUE / 10 || n == Integer.MAX_VALUE / 10 && i > 8)
return -1; // out of boundary
n = n * 10 + i;
}
return n;
}
}Last updated