From e0c1e2e31784dfb13ea8f710ff216bcdccf5d3bf Mon Sep 17 00:00:00 2001 From: zhangrunzhe Date: Mon, 21 Oct 2024 19:02:33 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E9=9D=A2=E8=AF=95=E9=A2=9802.07.=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9B=B8=E4=BA=A4=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/面试题02.07.链表相交.md | 39 +++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index b0f2e8ea..48944b5e 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -535,6 +535,45 @@ public ListNode GetIntersectionNode(ListNode headA, ListNode headB) } ``` +### Swift: +```swift +func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? { + var lenA = 0 + var lenB = 0 + var nodeA = headA + var nodeB = headB + // 计算链表A和链表B的长度 + while nodeA != nil { + lenA += 1 + nodeA = nodeA?.next + } + while nodeB != nil { + lenB += 1 + nodeB = nodeB?.next + } + // 重置指针 + nodeA = headA + nodeB = headB + // 如果链表A更长,让它先走lenA-lenB步 + if lenA > lenB { + for _ in 0..<(lenA - lenB) { + nodeA = nodeA?.next + } + } else if lenB > lenA { + // 如果链表B更长,让它先走lenB-lenA步 + for _ in 0..<(lenB - lenA) { + nodeB = nodeB?.next + } + } + // 同时遍历两个链表,寻找交点 + while nodeA !== nodeB { + nodeA = nodeA?.next + nodeB = nodeB?.next + } + return nodeA +} +``` +

From 2ddf04ff1432c5a3f0fdf81061913a5c7fcccd47 Mon Sep 17 00:00:00 2001 From: zhangrunzhe Date: Thu, 24 Oct 2024 18:04:48 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E5=8F=B3=E6=97=8B=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=E4=B8=B2=20swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/kamacoder/0055.右旋字符串.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/kamacoder/0055.右旋字符串.md b/problems/kamacoder/0055.右旋字符串.md index 363d9ffa..2b32cb44 100644 --- a/problems/kamacoder/0055.右旋字符串.md +++ b/problems/kamacoder/0055.右旋字符串.md @@ -350,7 +350,29 @@ function reverseStr(s, start, end) { ### Swift: +```swift +func rotateWords(_ s: String, _ k: Int) -> String { + var chars = Array(s) + // 先反转整体 + reverseWords(&chars, start: 0, end: s.count - 1) + // 反转前半段 + reverseWords(&chars, start: 0, end: k - 1) + // 反转后半段 + reverseWords(&chars, start: k, end: s.count - 1) + return String(chars) +} +// 反转start...end 的字符数组 +func reverseWords(_ chars: inout [Character], start: Int, end: Int) { + var left = start + var right = end + while left < right, right < chars.count { + (chars[left], chars[right]) = (chars[right], chars[left]) + left += 1 + right -= 1 + } +} +``` ### PHP: