-
Notifications
You must be signed in to change notification settings - Fork 277
/
NextGreaterElementIII.java
61 lines (47 loc) · 1.45 KB
/
NextGreaterElementIII.java
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
54
55
56
57
58
59
60
61
class NextGreaterElementIII {
// O(n), when n is the no of digits in n
public int nextGreaterElement(int n) {
char[] str = (n+"").toCharArray();
int deflectionPoint = str.length-1;
while(deflectionPoint>0){
if(str[deflectionPoint] > str[deflectionPoint-1]) {
break;
}
deflectionPoint--;
}
if(deflectionPoint == 0){
return -1;
}
int firstSwappingIndex = deflectionPoint -1;
int secondSwappingIndex = str.length -1;
while(secondSwappingIndex>=firstSwappingIndex){
if(str[firstSwappingIndex] < str[secondSwappingIndex]) {
break;
}
secondSwappingIndex--;
}
// swap
char temp = str[firstSwappingIndex];
str[firstSwappingIndex] = str[secondSwappingIndex];
str[secondSwappingIndex] = temp;
// swapping at the point of deflection
reverseChar(str, deflectionPoint);
Long no = Long.parseLong(new String(str));
if(no<=Integer.MAX_VALUE){
return no.intValue();
} else{
return -1;
}
}
private void reverseChar(char[] str, int i){
int start = i;
int end =str.length-1;
while(end>=start){
char temp = str[start];
str[start] = str[end];
str[end] = temp;
end--;
start++;
}
}
}