Skip to content

Commit e8be55f

Browse files
authored
Create Solution.java
1 parent 0af5480 commit e8be55f

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public int nextGreaterElement(int n) {
3+
if (n < 12) {
4+
return -1;
5+
}
6+
char[] cs = String.valueOf(n).toCharArray();
7+
int i = cs.length - 2;
8+
while (i >= 0 && cs[i] >= cs[i + 1]) {
9+
--i;
10+
}
11+
if (i < 0) {
12+
return -1;
13+
}
14+
int j = cs.length - 1;
15+
while (cs[i] >= cs[j]) {
16+
--j;
17+
}
18+
swap(cs, i, j);
19+
reverse(cs, i + 1, cs.length - 1);
20+
long res = 0;
21+
for (char c : cs) {
22+
res = res * 10 + c - '0';
23+
}
24+
return res <= Integer.MAX_VALUE ? (int) res : -1;
25+
}
26+
27+
private void reverse(char[] cs, int i, int j) {
28+
while (i < j) {
29+
swap(cs, i++, j--);
30+
}
31+
}
32+
33+
private void swap(char[] cs, int i, int j) {
34+
char tmp = cs[i];
35+
cs[i] = cs[j];
36+
cs[j] = tmp;
37+
}
38+
}

0 commit comments

Comments
 (0)