1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/swift/merge-k-sorted-lists.swift
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +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
}
}