Skip to content

141. Linked List Cycle #2

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion arai60/141. Linked List Cycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Solution:
#### 思考ログ
- LinkedListというデータ構造をよく理解できていなかった
- 普段のコーディングでポインタという概念をあまり意識していないなと思った
- わからなかったのであらいさんの回答をみた

# step2
```python
Expand Down Expand Up @@ -54,4 +55,38 @@ class Solution:
```
#### 思考ログ
- step2と同じ
- 回答わかっているのになぜ3回連続なんだろうと思ったが、確かに詰まっているところはしっかり理解しきれていないところだと思った。
- 回答わかっているのになぜ3回連続なんだろうと思ったが、確かに詰まっているところはしっかり理解しきれていないところだと思った。

# step4
```python
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if head is None :
return False
fast = slow = head

Choose a reason for hiding this comment

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

好みの問題ですが、自分だったらslow = fast = head (小さい、遅い方を先に持ってくる)の書き方にするかと思います。

while fast is not None and fast.next is not None:
Copy link

@Mike0121 Mike0121 Jul 24, 2024

Choose a reason for hiding this comment

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

可読性を考えると、while fast and fast.nextで良いと思いました。

fast = fast.next.next
slow = slow.next
if fast is slow:
return True
return False
```

#### ハッシュテーブル
```python
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
visited_nodes = set()
current_node = head

Choose a reason for hiding this comment

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

好みですが、今回コードが短くスコープが狭いので、visited, currentでも良いかなと思いました。
変数の長さに関して下記に参考になるかと思います。
https://discord.com/channels/1084280443945353267/1200089668901937312/1209882689411223644

while current_node:
if current_node in visited_nodes:
return True
visited_nodes.add(current_node)
current_node = current_node.next
return False
```

#### 思考ログ
- レビューで指摘された点を修正
- ハッシュテーブルの回答もみて写経してみた
- こちらのほうが思いつきやすそうだなという印象