problem
solution
option 1 - merge lists
用for 迴圈遍歷,並兩兩linked list 合併
1 | class Solution { |
option 2 - heap
建立一個 priority_queue
來儲存每個linked list的頭。
在遍歷pq,每次從priority_queue
取出最小的linked list 頭,從priority_queue
pop,再儲存linked list head->next。直到priority_queue
為空
priority_queue
排序可理解成return a->val > b->val;
從大排到小,但從尾部開始pop,所以每次取出的是最小的
1 | class Solution { |
heap pop
O(logn)
heap pushO(logn)
analysis
- option 1 merge
- time complexity
O(n^2)
- space complexity
O(nk)
- time complexity
- option 2 heap
- time complexity
O(nlogk)
- space complexity
O(n)k
- time complexity