some more problems solved
This commit is contained in:
26
linked-list-cycle/sol.go
Normal file
26
linked-list-cycle/sol.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func hasCycle(head *ListNode) bool {
|
||||
exists := map[*ListNode]bool{}
|
||||
current := head
|
||||
for current != nil {
|
||||
exists[current] = true
|
||||
current = current.Next
|
||||
if exists[current] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
28
linked-list-cycle/sol_O(1)_mem.go
Normal file
28
linked-list-cycle/sol_O(1)_mem.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
type ListNode struct {
|
||||
Val int
|
||||
Next *ListNode
|
||||
}
|
||||
|
||||
// This solution uses O(1) memory, but
|
||||
// runtime duration is a bit more
|
||||
// unpredictable with a maximum complexity
|
||||
// of O(n^2) I think.
|
||||
/**
|
||||
* Definition for singly-linked list.
|
||||
* type ListNode struct {
|
||||
* Val int
|
||||
* Next *ListNode
|
||||
* }
|
||||
*/
|
||||
func hasCycle(head *ListNode) bool {
|
||||
slow, fast := head, head
|
||||
for fast != nil && fast.Next != nil {
|
||||
slow, fast = slow.Next, fast.Next.Next
|
||||
if slow == fast {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
Reference in New Issue
Block a user