您的位置:首页 > 产品设计 > UI/UE

LeetCode.23 Merge k Sorted Lists (对数组链表进行合并,归并排序 && 或者使用PriorityQueue实现)

2018-03-09 10:34 633 查看
题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
分析:/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//对多个有序的链表进行合并
//思路:类似归并排序,先合将队列拆成两部分,两部分继续拆分。之后合并两个小的队列几个
if(lists==null||lists.length==0) return null;
if(lists.length==1) return lists[0];

return mergeKListsCore(lists,0,lists.length-1);

}
public ListNode mergeKListsCore(ListNode [] list,int start,int end){
if(start<end){
int mid=(start+end)/2;
ListNode left=mergeKListsCore(list,start,mid);
ListNode right=mergeKListsCore(list,mid+1,end);
return mergeTwoList(left,right);
}else{
return list[start];
}
}

public ListNode mergeTwoList(ListNode head1,ListNode head2){

//两个链表合并
ListNode A=head1;
ListNode B=head2;

ListNode temp=new ListNode(0);
ListNode cur=temp;
while(A!=null&&B!=null){
if(A.val<B.val){
cur.next=A;
A=A.next;
}else{
cur.next=B;
B=B.next;
}
cur=cur.next;
}

//防止还有剩下的
while(A!=null){
cur.next=A;
cur=cur.next;
A=A.next;
}
while(B!=null){
cur.next=B;
cur=cur.next;
B=B.next;
}

return temp.next;
}

}PriorityQueue实现:/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
//使用优先队列PrirorityQueue实现,修改其中的对比内部类compare
//保证每次插入都是按从小插入

if(lists==null||lists.length==0) return null;

// //JAVA之前,使用匿名内部类。记得初始化队列长度
// PriorityQueue<ListNode> pq=new PriorityQueue<>(lists.length,new Comparator<ListNode>(){
// @Override
// public int compare(ListNode l1,ListNode l2){
// //在添加元素的时候就进行规则排序。升序
// if(l1.bal>l2.val){
// return 1;
// }else if(l1.val==l2.val){
// return 0;
// }else{
// return -1;
// }
// }
// });

//Java8后使用lambda表达式更加高效、简捷
PriorityQueue <ListNode> pq=new PriorityQueue<ListNode>(lists.length,(a,b)->a.val-b.val);

ListNode res=new ListNode(0);
ListNode cur=res;
for(ListNode node:lists){
//进行非空判断,防止里面存在空的子数组
if(node!=null){
//插入的时候已经进行了排序,最小的元素放在最前面
pq.add(node);
}
}

while(!pq.isEmpty()){
cur.next=pq.poll();
cur=cur.next;
if(cur.next!=null){
//将后面的元素继续插入队列
pq.add(cur.next);
}
}
return res.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐