File tree Expand file tree Collapse file tree 1 file changed +60
-1
lines changed Expand file tree Collapse file tree 1 file changed +60
-1
lines changed Original file line number Diff line number Diff line change @@ -20,9 +20,68 @@ Here are some examples. Inputs are in the left-hand column and its corresponding
20
20
## 思路
21
21
22
22
题意是
23
+ 这道题让我们求下一个排列顺序,由题目中给的例子可以看出来,如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况,可以参见之前的博客 Permutations。我们再来看下面一个例子,有如下的一个数组
23
24
24
- ``` java
25
+ 1 2 7 4 3 1
26
+
27
+ 下一个排列为:
28
+
29
+ 1 3 1 2 4 7
30
+
31
+ 那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:
32
+
33
+ 1 2 7 4 3 1
34
+
35
+ 1 2 7 4 3 1
25
36
37
+ 1 3 7 4 2 1
38
+
39
+ 1 3 1 2 4 7
40
+
41
+
42
+
43
+ ``` java
44
+ public void nextPermutation(int [] nums) {
45
+ // find first decreasing digit
46
+ int mark = - 1 ;
47
+ for (int i = nums. length - 1 ; i > 0 ; i-- ) {
48
+ if (nums[i] > nums[i - 1 ]) {
49
+ mark = i - 1 ;
50
+ break ;
51
+ }
52
+ }
53
+
54
+ if (mark == - 1 ) {
55
+ reverse(nums, 0 , nums. length - 1 );
56
+ return ;
57
+ }
58
+
59
+ int idx = nums. length- 1 ;
60
+ for (int i = nums. length- 1 ; i >= mark+ 1 ; i-- ) {
61
+ if (nums[i] > nums[mark]) {
62
+ idx = i;
63
+ break ;
64
+ }
65
+ }
66
+
67
+ swap(nums, mark, idx);
68
+
69
+ reverse(nums, mark + 1 , nums. length - 1 );
70
+ }
71
+
72
+ private void swap(int [] nums, int i, int j) {
73
+ int t = nums[i];
74
+ nums[i] = nums[j];
75
+ nums[j] = t;
76
+ }
77
+
78
+ private void reverse(int [] nums, int i, int j) {
79
+ while (i < j) {
80
+ swap(nums, i, j);
81
+ i++ ;
82
+ j-- ;
83
+ }
84
+ }
26
85
```
27
86
28
87
You can’t perform that action at this time.
0 commit comments