Skip to content

300 longest increasing subsequence#31

Open
tarinaihitori wants to merge 3 commits intomainfrom
300-longest-increasing-subsequence
Open

300 longest increasing subsequence#31
tarinaihitori wants to merge 3 commits intomainfrom
300-longest-increasing-subsequence

Conversation

@tarinaihitori
Copy link
Copy Markdown
Owner

```python
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if nums is None:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Type関数を使っても良いかもしれません。
https://docs.python.org/ja/3.13/library/functions.html#type

変数名も含めて読みやすいように変えてみる。
最初の`if not nums`はこのままだと、numsにNoneが渡されても0を返してしまう。型ヒントからnumsにNoneは来ないことがわかっているが、
もし来た場合、例外を出して早めにバグを顕在化してほしいなと思ったので、TypeErrorを出すようにした。
あと最近Design by Contractとか防御的プログラミングの概念を本(Good Code, Bad Code)で学習したので、このあたりはチームの方針にもよるのかなと思った。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

「ユーザーフェイシングかどうか」など何を作っているかの状況によるかと思います。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.q026dzgqj28b

tails = []
for num in nums:
insert_position = bisect_left(tails, num)
if insert_position == len(tails):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私は、insert_position < len(tails) を条件にして上下入れ替えると思いますが、趣味の範囲ですね。

return len(tails)
```

ほかにも Fenwick Tree(Binary Indexed Tree)やセグメントツリーを使っても解けるらしいが、
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

セグメントツリーはアイディアとしてどういう構造化を知っておくといいかもしれません(、私も、使わない問題でも発想の過程で使ったりします)が、知らなくても構わないくらいかと思います。パズルとして出題しやすい子なんですよ。

left = 0
right = len(tails)
while left < right:
mid = left + (right - left) // 2
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Python では int 型は多倍長整数で実装されています。そのため、オーバーフローを回避するような書き方はする必要がなく、 mid = (left + right) // 2 とシンプルに書いてしまって大丈夫だと思います。

if nums is None:
raise TypeError("nums must be a List, not None")
if len(nums) == 0:
return 0
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この処理はなくても動きますね。

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.

5 participants