-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
85 lines (75 loc) · 2.23 KB
/
NextPermutation.java
File metadata and controls
85 lines (75 loc) · 2.23 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package leetcode;
/**
* NextPermutation
* https://leetcode-cn.com/problems/next-permutation/
* 31. 下一个排列
* 关键: 结尾倒序子序列
*
* @since 2020-11-10
*/
public class NextPermutation {
public static void main(String[] args) {
NextPermutation sol = new NextPermutation();
int[] a = new int[]{1, 2, 3};
sol.nextPermutation(a);
for (int i : a) {
System.out.print(i + ", ");
}
System.out.println();
int[] b = new int[]{3, 2, 1};
sol.nextPermutation(b);
for (int i : b) {
System.out.print(i + ", ");
}
System.out.println();
int[] c = new int[]{1, 2, 4, 3, 5};
sol.nextPermutation(c);
for (int i : c) {
System.out.print(i + ", ");
}
System.out.println();
int[] d = new int[]{1, 1, 5};
sol.nextPermutation(d);
for (int i : d) {
System.out.print(i + ", ");
}
System.out.println();
}
public void nextPermutation(int[] nums) {
int inv_first_idx = nums.length - 1;
// get inv first idx
while (inv_first_idx > 0) {
int next = inv_first_idx - 1;
if (nums[next] < nums[inv_first_idx]) {
break;
}
inv_first_idx = next;
}
// swap
if (inv_first_idx > 0) {
int swap_idx = inv_first_idx - 1;
int to_swap_idx = nums.length - 1;
while (to_swap_idx > swap_idx) {
if (nums[to_swap_idx] > nums[swap_idx]) {
break;
}
to_swap_idx--;
}
int tmp = nums[swap_idx];
nums[swap_idx] = nums[to_swap_idx];
nums[to_swap_idx] = tmp;
}
// resort inv sub seq
// just inv seq
int positive_idx = inv_first_idx;
int negative_idx = nums.length - 1;
int mid_idx = (positive_idx + negative_idx) / 2;
while (positive_idx <= mid_idx) {
int tmp = nums[positive_idx];
nums[positive_idx] = nums[negative_idx];
nums[negative_idx] = tmp;
positive_idx++;
negative_idx--;
}
}
}