problems(swift): add “23. Merge k Sorted Lists”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-10 23:25:37 +01:00
parent c1f7120274
commit 5fd8a18ef0
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -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..<lists.count {
if lists[i]!.val < lists[minIdx]!.val {
minIdx = i
}
}
// insert the list into the node
node.next = lists[minIdx]
node = lists[minIdx]!
// shift the list at the index or remove it
if lists[minIdx]!.next == nil {
lists.remove(at: minIdx)
} else {
lists[minIdx] = lists[minIdx]!.next
}
}
return root.next
}
}