mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(swift): add “23. Merge k Sorted Lists”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
c1f7120274
commit
5fd8a18ef0
1 changed files with 41 additions and 0 deletions
41
problems/swift/merge-k-sorted-lists.swift
Normal file
41
problems/swift/merge-k-sorted-lists.swift
Normal 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
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue