Created
January 19, 2020 12:40
-
-
Save spurscho/ceb5e8ef8dbdf753f48c09d98c092e2b to your computer and use it in GitHub Desktop.
23. Merge k Sorted Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* public class ListNode { | |
* public var val: Int | |
* public var next: ListNode? | |
* public init(_ val: Int) { | |
* self.val = val | |
* self.next = nil | |
* } | |
* } | |
*/ | |
class Solution { | |
func mergeKLists(_ lists: [ListNode?]) -> ListNode? { | |
guard lists.count > 0, lists != nil else { return nil } | |
var resArr = [Int]() | |
var currentNode: ListNode? | |
for node in lists { | |
guard node != nil else { | |
continue | |
} | |
currentNode = node | |
while currentNode != nil { | |
resArr.append(currentNode!.val) | |
currentNode = currentNode?.next | |
} | |
} | |
guard resArr.count > 0 else { | |
return nil | |
} | |
resArr.sort() | |
var resNode: ListNode? = ListNode(resArr[0]) | |
var currNode = resNode | |
for idx in 1 ..< resArr.endIndex { | |
currNode?.next = ListNode(resArr[idx]) | |
currNode = currNode?.next | |
} | |
return resNode | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment