File tree Expand file tree Collapse file tree 2 files changed +23
-13
lines changed
Algorithms/0142.linked-list-cycle-ii Expand file tree Collapse file tree 2 files changed +23
-13
lines changed Original file line number Diff line number Diff line change @@ -5,21 +5,26 @@ import "github.com/aQuaYi/LeetCode-in-Go/kit"
55// ListNode is pre-defined...
66type ListNode = kit.ListNode
77
8+ // https://leetcode.com/problems/linked-list-cycle-ii/discuss/44793/O(n)-solution-by-using-two-pointers-without-change-anything
89func detectCycle (head * ListNode ) * ListNode {
9- headPre := & ListNode {
10- Next : head ,
10+ if head == nil {
11+ return nil
1112 }
12- return detect (headPre )
13- }
14-
15- func detect (head * ListNode ) * ListNode {
16- hasSeen := make (map [* ListNode ]bool )
17- for head != nil && head .Next != nil {
18- if hasSeen [head .Next ] {
19- return head .Next
13+ slow , fast := head , head
14+ for fast != nil && fast .Next != nil {
15+ slow , fast = slow .Next , fast .Next .Next
16+ if slow == fast {
17+ break
2018 }
21- hasSeen [head .Next ] = true
22- head = head .Next
2319 }
24- return nil
20+
21+ if slow != fast {
22+ return nil
23+ }
24+
25+ slow = head
26+ for slow != fast {
27+ slow , fast = slow .Next , fast .Next
28+ }
29+ return slow
2530}
Original file line number Diff line number Diff line change @@ -14,6 +14,11 @@ var tcs = []struct {
1414 pos int
1515}{
1616
17+ {
18+ []int {1 },
19+ - 1 ,
20+ },
21+
1722 {
1823 []int {1 , 2 , 3 },
1924 - 1 ,
You can’t perform that action at this time.
0 commit comments