23. Merge k Sorted Lists
Hard
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:
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:
Input: lists = []
Output: []
Example 3:
Input: lists = [[]]
Output: []
Constraints:
- 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 exceed 104.
문제 풀이
정렬된 링크드 리스트가 들어간 배열이 주어진다.
여러개의 링크드 리스트를 가지고 하나의 정렬된 링크드 리스트를 만들어야한다.
모든 리스트의 노드들을 우선순위 큐, 즉 힙에 넣는다.
힙에서 하나씩 빼어 답을 구성한다.
소스 코드
# 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: List[Optional[ListNode]]) -> Optional[ListNode]:
ans = None
total = []
heapify(total)
for l in lists:
cur = l
while cur:
heappush(total, cur.val)
cur = cur.next
if len(total) == 0:
return ans
ans = ListNode(heappop(total), None)
temp = ans
while total:
temp.next = ListNode(heappop(total), None)
temp = temp.next
return ans
'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글
[LeetCode] 84. Largest Rectangle in Histogram (0) | 2022.11.09 |
---|---|
[LeetCode] 25. Reverse Nodes in k-Group (1) | 2022.11.03 |
[LeetCode - Biweekly Contest 90]2454. Next Greater Element IV (0) | 2022.11.01 |
[LeetCode - Biweekly Contest 90] 2453. Destroy Sequential Targets (0) | 2022.11.01 |
[LeetCode - Biweekly Contest 90] 2451. Odd String Difference (0) | 2022.11.01 |