您的位置:首页 > 其它

合并k个排序链表

2016-07-12 16:02 351 查看

题目

合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。

样例

给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null

解题

两两合并

合并ab得到c

合并cd得到e

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if(lists == null || lists.size()==0)
return null;
ListNode head = lists.get(0);
for(int i=1;i<lists.size();i++){
ListNode list = lists.get(i);
if(list!=null)
head = merge(head,list);
}
// print(head);
return head;
}
public void print(ListNode head){
while(head!=null){
System.out.print(head.val + "->");
head = head.next;
}
System.out.println();
}
public ListNode merge(ListNode l1,ListNode l2){
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode head = new ListNode(-1);
ListNode cur = head;
while(l1!=null && l2!=null){
if(l1.val <=l2.val){
cur.next = l1;
l1 = l1.next;
}else{
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
if(l1!=null)
cur.next = l1;
if(l2!=null)
cur.next = l2;
return head.next;
}
}


利用优先队列

public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if(lists == null || lists.size()==0)
return null;
ListNode head = new ListNode(0);
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
public int compare(ListNode a ,ListNode b){
if(a.val > b.val)
return 1;
else if(a.val == b.val)
return 0;
return -1;
}
});
for(ListNode list:lists){
if(list!=null)
q.add(list);
}
ListNode p = head;
while(q.size() >0){
ListNode tmp = q.poll();
p.next = tmp;
if(tmp.next!=null){
q.add(tmp.next);
}
p = p.next;
}
return head.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: