Explore diversas soluciones LeetCode en Python, C++, JavaScript, SQL y TypeScript. Ideal para preparación de entrevistas, aprendizaje y práctica de código en múltiples lenguajes de programación. Enlace de repositorio de Github
You are given an array of k
linked-lists liza
, each linked-list is sorted in ascending order.
Fusione todas las listas vinculadas en una lista vinculada ordenada y devuélvala.
Ejemplo 1:
Aporte: lists = [[1,4,5],[1,3,4],[2,6]] Producción: [1,1,2,3,4,4,5,6] Explicación: 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
Ejemplo 2:
Aporte: lists = [] Producción: []
Ejemplo 3:
Aporte: lists = [[]] Producción: []
Restricciones:
k == lists.length
0 <= k <= 104
0 <= lists[i].length <= 500
-104 <= lists[i][j] <= 104
lists[i]
is sorted in ascending order.- The sum of
lists[i].length
will not exceed104
.
Pitón
# Definition for singly-linked list.
from typing import List, Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
nodes = []
head = point = ListNode(0)
for left in lists:
while left:
nodes.append(left.val)
left = left.next
for x in sorted(nodes):
point.next = ListNode(x)
point = point.next
return head.next