/Merge k Sorted Lists Total Accepted: 38333 Total Submissions: 181458 My Submissions Question Solution
//Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
//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;
* next = null;
* }
* }
*/
public class MergekSortedLists {
public static void main(String[] args) {
// TODO 自动生成的方法存根
}
public ListNode mergeKLists(List
lists) {
if(lists==null)
return null;
PriorityQueue pq=new PriorityQueue(new Comparator(){
//有正负就行
@Override
public int compare(ListNode o1, ListNode o2) {
// TODO 自动生成的方法存根
return o1.val-o2.val;
}
});
//遍历每一个
for(ListNode list:lists)
//有可能有空,空的不能加进去
if(list!=null)
pq.add(list);
ListNode head=new ListNode(0);
ListNode p=head;
while(!pq.isEmpty()){
ListNode cur=pq.poll();
p.next=cur;
if(cur.next!=null)
pq.add(cur.next);
p=cur;
}
return head.next;
}
}
阅读(330) | 评论(0) | 转发(0) |