-
Notifications
You must be signed in to change notification settings - Fork 0
31. Next Permutation #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
| end | ||
| nil | ||
| end | ||
| rfind_first_greater_than = lambda do |target| |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
一応ここは二分探索が使えますね。(pivot_indexの一つ右からnumsの最後までは降順にソートされているので)
| right -= 1 | ||
| end | ||
| end | ||
| rfind_first_ascending = lambda do |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
右から見ていったときにはascendingではなくdescendingなのでちょっとややこしい気がします。(firstという単語のニュアンスでは右から見ている感じなので)
参考までに、c++ではis_sorted_untilという関数があったりします。そこから名前を取って、rfind_is_sorted_untilとかでもいいかもしれません。
あと、個人的にはnums.size - 1から初めてnums[i]とnums[i-1]の比較をしたいかもしれません。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
コメントありがとうございます!
is_sorted_until良いですね。
| nums.reverse! | ||
| return | ||
| end | ||
| swap_index = rfind_first_greater_than.call(nums[pivot_index]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rfind_first_greater_than を使わずに以下のようにも書けると思いました。
swap_index = nums.rindex { |num| num > nums[pivot_index] }http://docs.ruby-lang.org/ja/latest/class/Array.html#I_RINDEX
折に触れてドキュメントを見ると発見があるかもしれません。
| nums[pivot_index], nums[swap_index] = nums[swap_index], nums[pivot_index] | ||
| reverse.call(pivot_index + 1, nums.size - 1) | ||
| end | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lambda の定義の間には1行空行があった方が読みやすいと感じました。
解いた問題
31. Next Permutation
使用言語
Ruby
次に解く問題
8. String to Integer (atoi)