Open
Conversation
nodchip
reviewed
Jun 10, 2024
| class Solution: | ||
| def lengthOfLIS(self, nums: List[int]) -> int: | ||
| lis_so_far = [1] * len(nums) # lis: longest increasing subsequence | ||
| for i in range(len(nums)-1): |
There was a problem hiding this comment.
| lis_so_far = [1] * len(nums) # lis: longest increasing subsequence | ||
| for i in range(len(nums)-1): | ||
| for j in range(i+1, len(nums)): | ||
| if nums[i] < nums[j] and lis_so_far[j] < lis_so_far[i] + 1: |
| class Solution: | ||
| def lengthOfLIS(self, nums: List[int]) -> int: | ||
| MAX_NUM = 10 ** 4 | ||
| increasing_subsequence = [MAX_NUM + 1] * len(nums) |
There was a problem hiding this comment.
個人的には長さ 0 から始めて、どこにも挿入できない場合は末尾に追加する、といったロジックのほうが好みです。ですが、好みの問題だと思います。
There was a problem hiding this comment.
私は、10 ** 4 が(問題文の制約からくる)マジックナンバーであることが気になりますね。1でも大きくなったら動かなくなるわけですよねえ。
Owner
Author
There was a problem hiding this comment.
確かにそうですね, 訂正いたします。ところで, 逆にマジックナンバーをあえて使う場面などはあるのでしょうか...?
There was a problem hiding this comment.
いや、読み手が分かるように書くので、マジックナンバーになったらコメントを書いてください。
有名なマジックナンバーとしては 0x5f3759df があります。
https://en.wikipedia.org/wiki/Fast_inverse_square_root
| for j in range(i): | ||
| if nums[j] < nums[i]: | ||
| lis_so_far[i] = max(lis_so_far[i], lis_so_far[j] + 1) | ||
| max_lis = max(max_lis, lis_so_far[i]) |
There was a problem hiding this comment.
step2 のように、最後に 1 回 max() 関数を使ったほうがシンプルで読みやすい思います。
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.
問題
300. Longest Increasing Subsequence