some more problems solved

This commit is contained in:
2022-06-04 12:25:07 +01:00
parent 6a5f3eccaf
commit e028f4cf94
8 changed files with 273 additions and 0 deletions

26
linked-list-cycle/sol.go Normal file
View 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
}

View 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
}