File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
solution/0556.Next Greater Element III Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments