From 5fd8a18ef051db60c8110fc248c99e985dcf7a32 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 10 Dec 2023 23:25:37 +0100 Subject: [PATCH] =?UTF-8?q?problems(swift):=20add=20=E2=80=9C23.=20Merge?= =?UTF-8?q?=20k=20Sorted=20Lists=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/swift/merge-k-sorted-lists.swift | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 problems/swift/merge-k-sorted-lists.swift diff --git a/problems/swift/merge-k-sorted-lists.swift b/problems/swift/merge-k-sorted-lists.swift new file mode 100644 index 0000000..a3108fc --- /dev/null +++ b/problems/swift/merge-k-sorted-lists.swift @@ -0,0 +1,41 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +class Solution { + func mergeKLists(_ lists: [ListNode?]) -> ListNode? { + var lists = lists.filter { $0 != nil } + let root = ListNode() + + var node = root + while !lists.isEmpty { + // find the next list + var minIdx = 0 + for i in 1..