LeetCode/problems/swift/merge-k-sorted-lists.swift
Matej Focko 5fd8a18ef0
problems(swift): add “23. Merge k Sorted Lists”
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-10 23:25:37 +01:00

41 lines
1.1 KiB
Swift

/**
* 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
}
}