Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

23. Merge k Sorted Lists

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

Example 1:

1
2
3
4
5
6
7
8
9
10
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

1
2
3
4
5
6
Input: lists = []
Output: []
Example 3:

Input: lists = [[]]
Output: []

讀到陣列排序後丟回去。

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
27
28
29
30
31
32
Time: O(n), Space: O(n)

# Definition for singly-linked list.
# class ListNode:
# def init(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
res = []
for x in lists:
while x:
res.append(x.val)
x=x.next

if not res: return

# sort the result list
res = sorted(res)

# push all the values from the list to the final linked list
head = ListNode(res[0])
node = head
for x in res[1:]:
node.next = ListNode(x)
node = node.next
return head

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels