Merged
Conversation
hayashi-ay
reviewed
Apr 23, 2024
| if nums[target_index] < nums[i] < min_num: | ||
| min_num = nums[i] | ||
| index = i | ||
| return index |
There was a problem hiding this comment.
forループ内のif文に入らない場合、何が返りますか?読んでいて不安になりました。やっぱりfor文の中でしか定義していない変数をfor文の外で使うのは気になります。
Owner
Author
There was a problem hiding this comment.
left = find_index_not_asc_from_end(nums)の処理をすれば、find_index_next_largerがif文に入らないケースはなくなるので、雑に書いてしまいました。
関数単体で見ても問題がないようにすることが望ましいのですね。
今回の場合は、indexの初期値を作っておいて例外の処理を書くのかなと思いました。
def find_index_next_larger(nums, target_index):
min_num = math.inf
index = -1
for i in range(target_index + 1, len(nums)):
if nums[target_index] < nums[i] < min_num:
min_num = nums[i]
index = i
return indexThere was a problem hiding this comment.
まあコメントがあるだけでも良いかもです。それだけでforの中のif文がちゃんと呼ばれるよね、と確認する手間が減ります。
hayashi-ay
reviewed
Apr 24, 2024
| return | ||
| right = find_index_next_larger(nums, left) | ||
| nums[left], nums[right] = nums[right], nums[left] | ||
| nums[left + 1 :] = sorted(nums[left + 1 :]) |
There was a problem hiding this comment.
L17のmin_numとの比較を<=に変えてあげれば、leftの右側は降順になるので単純にreverseするだけでよくなります。
今回は値が同じ場合を考慮してあげる必要があるのが少し違いますが、前回のコメントと同様ですね。
#50 (comment)
Owner
Author
There was a problem hiding this comment.
reverseでやりたいけど同値でできないと思っていたのですが、ありがとうございます。
oda
reviewed
Apr 24, 2024
| right = i | ||
| nums[left], nums[right] = nums[right], nums[left] | ||
| nums[left + 1 :] = sorted(nums[left + 1 :]) | ||
| break |
Owner
Author
There was a problem hiding this comment.
breakにした特別な意図はないです。
値を返す問題ではなかったので、ここでreturnしようという発想がありませんでした。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題
https://leetcode.com/problems/next-permutation/