1. 程式人生 > >leetcode 23 合併n個連結串列

leetcode 23 合併n個連結串列

Definition for singly-linked list.

Merge K Sorted Lists (#23)

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

程式碼

class Solution
(object):
def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ now = [] head = point = ListNode(0) for i in lists: while i : now.append(i.val) i = i.next for i in
sorted(now): point.next = ListNode(i) point = point.next return head.next