您的位置:首页 > 其它

【Leetcode】Merge K Sorted Linked List

2015-07-16 21:39 281 查看
【题目】

Merge k sorted Linked Lists and return it as one sorted lists. Analyze and describe its complexity .

【思路】

leetcode clean book

【代码】 private static final Comparator<ListNode> listComparator = new Comparator<ListNode>(){
public int compare(ListNode x, ListNode y){
return x.val - y.val;
}
};

public static ListNode mergeK(List<ListNode> list){
if(list.isEmpty()) return null;
Queue<ListNode> queue = new PriorityQueue<>(list.size(),listComparator);
for(ListNode node : list){
if(node!=null){
queue.add(node);
}
}
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while(!queue.isEmpty()){
ListNode node = queue.poll();
p.next = node;
p=p.next;
if(node.next!=null){
queue.add(node.next);
}
}
return dummy.next;

}
public static ListNode mergeK2(List<ListNode> list){
if (list == null) return null;
int end = list.size() - 1;
while(end > 0){
int start = 0;
while(start < end){
list.set(start, merge2List(list.get(start),list.get(end)));
start++;
end--;
}
}
return list.get(0);
}

public static ListNode merge2List(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
ListNode p = l1, q = l2;
while(p != null && q != null){
if(p.val > q.val ){
cur.next = q;
q = q.next;
}else{
cur.next = p;
p = p.next;
}
cur = cur.next;
}
if(p!=null) cur.next = p;
if(q!=null) cur.next = q;

return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode