Merge k sorted list
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析
K路归并,用priority queue, 注意loop array时候,null的element不要加入queue
public ListNode mergeKLists(ListNode[] lists) {
if(lists == null || lists.length == 0)
return null;
int k = lists.length;
Queue<ListNode> q = new PriorityQueue<ListNode>(k, new Comparator<ListNode>(){
public int compare(ListNode a, ListNode b){
return a.val - b.val;
}
});
for(ListNode e : lists){
if(e != null)
q.offer(e);
}
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while(!q.isEmpty()){
cur = cur.next = q.poll();
if(cur != null && cur.next != null){
q.offer(cur.next);
}
}
return dummy.next;
}python, 用tuple塞入heapq (node.val,node)
必须塞入list的index入tuple,防止value相同时候,错半死!!!
Last updated
Was this helpful?