-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
63 lines (59 loc) · 1.36 KB
/
Copy pathSolution.java
File metadata and controls
63 lines (59 loc) · 1.36 KB
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
62
63
public class Solution
{
private int min;
public int nextGreaterElement(int num)
{
min = Integer.MAX_VALUE;
int[] counts = new int[10];
int len = 0;
int trgt = num;
while (num > 0)
{
int digit = num % 10;
counts[digit]++;
num /= 10;
len++;
}
findMin(counts, len, 0, trgt, 0);
if (min == Integer.MAX_VALUE)
{
return -1;
}
return min;
}
private void findMin(int[] counts, int len, int currLen, int num, int curr)
{
if (currLen == len)
{
if (curr > num)
{
min = Math.min(curr, min);
}
return;
}
for (int i = 0; i <= 9; i++)
{
if (counts[i] != 0)
{
int k = counts[i];
while (k > 0)
{
int[] arr = getArray(counts);
arr[i]--;
int tmp = curr * 10 + i;
findMin(arr, len, currLen + 1, num, tmp);
k--;
}
}
}
}
private int[] getArray(int[] counts)
{
int[] ret = new int[10];
for (int i = 0; i <= 9; i++)
{
ret[i] = counts[i];
}
return ret;
}
}