Skip to content

Commit 9f22efe

Browse files
committed
refactor next permutation
1 parent 064f2f9 commit 9f22efe

File tree

1 file changed

+22
-11
lines changed

1 file changed

+22
-11
lines changed

go/next_permutation.go

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,37 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4+
// [1, 3, 5, 4, 2]という入力があるとき
5+
// 3 < 5なので、3を変える必要がある
6+
// 3より大きい最小の値は4なので、3と4を入れ替えると
7+
// [1, 4, 5, 3, 2]となる
8+
// 3以降の要素を逆順にすると、
9+
// next permutationの[1, 4, 2, 3, 5]となる。
10+
// nums[isSortedUntil] >= nums[isSortedUntil+1]は>ではなく、>=でないと
11+
// [1, 1]などではOut of indexになる
412
func nextPermutation(nums []int) {
5-
if len(nums) < 2 {
13+
if len(nums) <= 1 {
614
return
715
}
8-
i := len(nums) - 2
9-
for i >= 0 && nums[i] >= nums[i+1] {
10-
i--
16+
isSortedUntil := len(nums) - 2
17+
for isSortedUntil >= 0 && nums[isSortedUntil] >= nums[isSortedUntil+1] {
18+
isSortedUntil--
1119
}
12-
if i >= 0 {
13-
j := len(nums) - 1
14-
for nums[j] <= nums[i] {
15-
j--
20+
if isSortedUntil >= 0 {
21+
swapTarget := len(nums) - 1
22+
for nums[isSortedUntil] >= nums[swapTarget] {
23+
swapTarget--
1624
}
17-
nums[i], nums[j] = nums[j], nums[i]
25+
nums[isSortedUntil], nums[swapTarget] = nums[swapTarget], nums[isSortedUntil]
1826
}
19-
reverse(nums[i+1:])
27+
reverse(nums[isSortedUntil+1:])
2028
}
2129

2230
func reverse(nums []int) {
23-
for i, j := 0, len(nums)-1; i < j; i, j = i+1, j-1 {
31+
i, j := 0, len(nums)-1
32+
for i < j {
2433
nums[i], nums[j] = nums[j], nums[i]
34+
i++
35+
j--
2536
}
2637
}

0 commit comments

Comments
 (0)