Conversation
| if len(nums) < 2 { | ||
| return | ||
| } | ||
| i := len(nums) - 2 |
There was a problem hiding this comment.
iのスコープが少し広いので変数名をつけてほしいと思いましたが、いい名前が思いつきませんでした。すみません。
index_not_ascending_from_backだと長いですね。
There was a problem hiding this comment.
https://en.cppreference.com/w/cpp/algorithm/next_permutation
C++ だと is_sorted_until ですね。いくつかの関数に割ってもいいんじゃないでしょうか。
| */ | ||
| func nextPermutation_step2(nums []int) { | ||
| for i := len(nums) - 1; i > 0; i-- { | ||
| if nums[i-1] < nums[i] { |
There was a problem hiding this comment.
if nums[i-1] >= nums[i] {
break
}とすると early return できそうです。
もしかしたらプログラム全体で不等号の向きを < に揃えているかもしれませんが、直線として見たときに nums[i-1] < nums[i] と同じ分かりやすさなのは上記なのかなと思いました。
| if nums[i-1] < nums[i] { | ||
| candidate, candidateIndex := nums[i], i | ||
| for j := i; j < len(nums); j++ { | ||
| if nums[j] < candidate && nums[i-1] < nums[j] { |
There was a problem hiding this comment.
if nums[i-1] < nums[j] && nums[j] < candidate {だと位置関係がイメージしやすいのかなと思いました。
There was a problem hiding this comment.
この条件に入る nums[j] は既にcandidate より小さい気がします。
candidateIndex := i
for j := i; j < len(nums); j++ {
if nums[i-1] < nums[j] {
candidateIndex = j
}
}candidate を使っている箇所を省いて、上記のようにも書けそうです。
| for i := len(nums) - 1; i > 0; i-- { | ||
| if nums[i-1] < nums[i] { | ||
| candidate, candidateIndex := nums[i], i | ||
| for j := i; j < len(nums); j++ { |
There was a problem hiding this comment.
細かいかもしれませんが、
for j := i + 1; j < len(nums); j++ {
でもいいかもしれません。その上の条件で、j が i の場合はもう見ているのかなと思いました。
| return | ||
| } | ||
| } | ||
| sort.Slice(nums, func(a, b int) bool { |
There was a problem hiding this comment.
ここに入るのは、次の順列が全要素昇順のパターンというふうに理解しています。
そうだとしたら、そのパターンだけここで処理していることが分かるようにコメントなりがあると、何のために必要なのかが分かりやすくなるのかなと思いました。
Next Permutationを解きました。レビューをお願いいたします。
問題:https://leetcode.com/problems/next-permutation/
言語:Go
すでに解いた方々:
hayashi-ay/leetcode#67
shining-ai/leetcode#58
SuperHotDogCat/coding-interview#8
goto-untrapped/Arai60#12
Exzrgs/LeetCode#7
Mike0121/LeetCode#15