Skip to content

Commit 3e03f8b

Browse files
committed
142 wrong answer
1 parent 3fc5a06 commit 3e03f8b

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

Algorithms/0142.linked-list-cycle-ii/linked-list-cycle-ii.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,26 @@ import "github.com/aQuaYi/LeetCode-in-Go/kit"
55
// ListNode is pre-defined...
66
type 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
89
func 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
}

Algorithms/0142.linked-list-cycle-ii/linked-list-cycle-ii_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff 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,

0 commit comments

Comments
 (0)