Skip to content

141. Linked List Cycle#1

Open
hroc135 wants to merge 2 commits intomainfrom
sendahuang14-patch-1
Open

141. Linked List Cycle#1
hroc135 wants to merge 2 commits intomainfrom
sendahuang14-patch-1

Conversation

@hroc135
Copy link
Copy Markdown
Owner

@hroc135 hroc135 commented Jul 16, 2024

Copy link
Copy Markdown

@hayashi-ay hayashi-ay left a comment

Choose a reason for hiding this comment

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

訪れたノードをHash Tableで管理する方法でも解いてみると良いと思います。まずはこっちの解法が思いつくのかなと個人的には思います。

@hroc135
Copy link
Copy Markdown
Owner Author

hroc135 commented Jul 17, 2024

そうですね、実装してみました。

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
    // hash table
    visited := make(map[*ListNode]bool)
    for head != nil {
        _, exist := visited[head]
        if exist {
            return true
        }
        visited[head] = true
        head = head.Next
    }
    return false
}

hash tableを使った実装だとメモリ使用量がO(n)になるのに対して、tortoise and hareだとO(1)ですね。ただ、hash tableの方が自然な発想という感じがしますね

@hayashi-ay
Copy link
Copy Markdown

良いと思います。

```

### Step 2
- slow, fastという名前が変数名として微妙だと思い、slow pointerという意味でslowPtrとした(fastも同様)。
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://discord.com/channels/1084280443945353267/1196472827457589338/1249723841228439603
https://discord.com/channels/1084280443945353267/1201211204547383386/1222123409295675394

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ご指摘ありがとうございます。go言語はミニマリスト的な思想が強く、命名はなるべく短くすることが好まれるのですが、それによって失われるわかりやすさにも気をつけるようにしたいと思います

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://google.github.io/styleguide/go/decisions#naming
こういうところをまず引き、照らし合わせて論じましょう。

### Step 3
- 以下のページを参考にGoのポインタについて復習。手を動かしながら読んだので前より理解が深まった。
https://medium.com/@jamal.kaksouri/a-comprehensive-guide-to-pointers-in-go-4acc58eb1f4d

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私は、map に追加していくのが想定解と思うのと、あと Discord の中を漁って欲しいですね。こう、読む癖をつけるのがかなり大きな目的なので。

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