Skip to content

Conversation

@SuperHotDogCat
Copy link
Owner

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):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

step2 の書き方のほうがシンプルだと思います。

class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
MAX_NUM = 10 ** 4
increasing_subsequence = [MAX_NUM + 1] * len(nums)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

個人的には長さ 0 から始めて、どこにも挿入できない場合は末尾に追加する、といったロジックのほうが好みです。ですが、好みの問題だと思います。

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私は、10 ** 4 が(問題文の制約からくる)マジックナンバーであることが気になりますね。1でも大きくなったら動かなくなるわけですよねえ。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

確かにそうですね, 訂正いたします。ところで, 逆にマジックナンバーをあえて使う場面などはあるのでしょうか...?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いや、読み手が分かるように書くので、マジックナンバーになったらコメントを書いてください。

有名なマジックナンバーとしては 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])
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

step2 のように、最後に 1 回 max() 関数を使ったほうがシンプルで読みやすい思います。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants