From c555aa722dc64c4c0f6965f86a7bfa34391efe3e Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Mon, 3 Jun 2024 07:45:32 +0100 Subject: [PATCH] Swift implementation for LCOF2 022 --- .../README.md" | 36 +++++++++++++++++++ .../Solution.swift" | 31 ++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" index 1217b93230573..ae7cbf1a5b9bf 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/README.md" @@ -271,4 +271,40 @@ var detectCycle = function (head) { }; ``` +#### Swift + +```swift +/* class ListNode { +* var val: Int +* var next: ListNode? +* init(_ val: Int) { +* self.val = val +* self.next = nil +* } +* } +*/ + +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var fast = head + var slow = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + + if slow === fast { + var ans = head + while ans !== slow { + ans = ans?.next + slow = slow?.next + } + return ans + } + } + return nil + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/Solution.swift" new file mode 100644 index 0000000000000..2b0387e0e79d3 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 022. \351\223\276\350\241\250\344\270\255\347\216\257\347\232\204\345\205\245\345\217\243\350\212\202\347\202\271/Solution.swift" @@ -0,0 +1,31 @@ +/* class ListNode { +* var val: Int +* var next: ListNode? +* init(_ val: Int) { +* self.val = val +* self.next = nil +* } +* } +*/ + +class Solution { + func detectCycle(_ head: ListNode?) -> ListNode? { + var fast = head + var slow = head + + while fast != nil && fast?.next != nil { + slow = slow?.next + fast = fast?.next?.next + + if slow === fast { + var ans = head + while ans !== slow { + ans = ans?.next + slow = slow?.next + } + return ans + } + } + return nil + } +} \ No newline at end of file