Poison

556. Next Greater Element III

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public int nextGreaterElement(int n) {
if (n < 10) {
return -1;
}

char[] chars = String.valueOf(n).toCharArray();

int lowerIndex = -1;
for (int i = chars.length - 1; i > 0; i--) {
if (chars[i - 1] < chars[i]) {
lowerIndex = i - 1;
break;
}
}

if (lowerIndex != -1) {
for (int i = chars.length - 1; i > lowerIndex; i--) {
if (chars[i] > chars[lowerIndex]) {
swap(chars, i, lowerIndex);
reverse(chars, lowerIndex + 1, chars.length - 1);
break;
}
}
} else {
return -1;
}

int res = 0;
for (char c : chars) {
int num = c - '0';
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && num > 7)) {
return -1;
} else {
res = res * 10 + num;
}
}

return res;
}

private void reverse(char[] chars, int i, int j) {
while (i < j) {
swap(chars, i++, j--);
}
}

private void swap(char[] chars, int i, int j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}
Reference

556. Next Greater Element III