Skip to content

Commit 6f20766

Browse files
committed
二刷31
1 parent d5d1e67 commit 6f20766

File tree

3 files changed

+62
-9
lines changed

3 files changed

+62
-9
lines changed

docs/0031-next-permutation.adoc

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ https://leetcode.cn/problems/next-permutation/[LeetCode - 31. 下一个排列 ^]
4040
输出:[1,5,1]
4141
....
4242

43-
4443
*提示:*
4544

4645
* `+1 <= nums.length <= 100+`
@@ -83,17 +82,20 @@ include::{sourcedir}/_0031_NextPermutation.java[tag=answer]
8382
----
8483
--
8584
86-
// 二刷::
87-
// +
88-
// --
89-
// [{java_src_attr}]
90-
// ----
91-
// include::{sourcedir}/_0031_NextPermutation_2.java[tag=answer]
92-
// ----
93-
// --
85+
二刷::
86+
+
87+
--
88+
[{java_src_attr}]
89+
----
90+
include::{sourcedir}/_0031_NextPermutation_2.java[tag=answer]
91+
----
92+
--
9493
====
9594

9695

9796
== 参考资料
9897

98+
. https://leetcode.cn/problems/next-permutation/solutions/80560/xia-yi-ge-pai-lie-suan-fa-xiang-jie-si-lu-tui-dao-/[31. 下一个排列 - 思路+推导+步骤,看不懂算我输!^]
99+
. https://leetcode.cn/problems/next-permutation/solutions/479151/xia-yi-ge-pai-lie-by-leetcode-solution/[31. 下一个排列 - 官方题解^]
100+
99101

logbook/202503.adoc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,11 @@ endif::[]
383383
|{doc_base_url}/0662-maximum-width-of-binary-tree.adoc[题解]
384384
|⭕️ 添加虚拟节点的做法超时。看答案给节点加编号通过。
385385

386+
|{counter:codes}
387+
|{leetcode_base_url}/next-permutation/[31. Next Permutation^]
388+
|{doc_base_url}/0031-next-permutation.adoc[题解]
389+
|❌ 明白大概意思,思路不够条理,写不出代码。
390+
386391
|===
387392

388393
截止目前,本轮练习一共完成 {codes2503} 道题。
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.diguage.algo.leetcode;
2+
3+
public class _0031_NextPermutation_2 {
4+
// tag::answer[]
5+
/**
6+
* @author D瓜哥 · https://www.diguage.com
7+
* @since 2025-04-21 15:29:48
8+
*/
9+
public void nextPermutation(int[] nums) {
10+
int i = nums.length - 2;
11+
// 选择第一对升序数字,是降序就向前走。
12+
while (i >= 0 && nums[i] >= nums[i + 1]) {
13+
i--;
14+
}
15+
if (i >= 0) {
16+
// 如果找到了升序数字对,则从后向前寻找一个大于 nums[i] 的数字,然后交换
17+
int j = nums.length - 1;
18+
while (j >= 0 && nums[i] >= nums[j]) {
19+
j--;
20+
}
21+
swap(nums, i, j);
22+
}
23+
// 反转 i+1 的数字
24+
reverse(nums, i + 1);
25+
}
26+
27+
private void reverse(int[] nums, int index) {
28+
int left = index, right = nums.length - 1;
29+
while (left < right) {
30+
swap(nums, left, right);
31+
left++;
32+
right--;
33+
}
34+
}
35+
36+
private void swap(int[] nums, int i, int j) {
37+
int temp = nums[i];
38+
nums[i] = nums[j];
39+
nums[j] = temp;
40+
}
41+
// end::answer[]
42+
43+
public static void main(String[] args) {
44+
new _0031_NextPermutation_2().nextPermutation(new int[]{1, 5, 4, 3, 2});
45+
}
46+
}

0 commit comments

Comments
 (0)