Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ]
Output: 1->1->2->3->4->4->5->6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
func mergeKLists(_ lists: [ListNode?]) -> ListNode? { var i = 0, j = 0, fl = lists.compactMap({$0}), n = fl.count, p: ListNode? if n < 1 { return nil } var arr = Array(repeating: 0, count: 256*256) while i < n { p = fl[i]; i += 1 while let p1 = p { arr[j] = p1.val p = p1.next; j += 1 if p == nil, i < n { p1.next = fl[i] } } } arr = Array(arr[..<j]).sorted() i = 0; p = fl[0] while let q = p, i < j { q.val = arr[i] p = q.next; i += 1 } return fl[0] } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼