LeetCode/swift/merge-k-sorted-lists.swift

42 lines
1.1 KiB
Swift
Raw Normal View History

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