forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_556.java
58 lines (53 loc) · 1.52 KB
/
_556.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
package com.fishercoder.solutions;
/**
* 556. Next Greater Element III
*
* Given a positive 32-bit integer n, you need to find the smallest 32-bit integer which has exactly the same digits existing
* in the integer n and is greater in value than n. If no such positive 32-bit integer exists, you need to return -1.
*
* Example 1:
* Input: 12
* Output: 21
*
* Example 2:
* Input: 21
* Output: -1
*/
public class _556 {
//credit: https://discuss.leetcode.com/topic/85759/this-problem-is-the-same-to-next-permutation-algorithm-only and https://discuss.leetcode.com/topic/85755/java-solution-like-next-permutation-problem-o-n
public int nextGreaterElement(int n) {
char[] digits = String.valueOf(n).toCharArray();
int i = digits.length - 2;
while (i >= 0 && digits[i + 1] <= digits[i]) {
i--;
}
if (i < 0) {
return -1;
}
int j = digits.length - 1;
while (j >= 0 && digits[j] <= digits[i]) {
j--;
}
swap(digits, i, j);
reverse(digits, i + 1);
try {
return Integer.parseInt(new String(digits));
} catch (Exception e) {
return -1;
}
}
private void reverse(char[] a, int start) {
int i = start;
int j = a.length - 1;
while (i < j) {
swap(a, i, j);
i++;
j--;
}
}
private void swap(char[] a, int i, int j) {
char temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}