Merge k sorted linked lists and return it as one sorted list. Analyze
and describe its complexity.Example:算法
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
要減少算法的複雜度,就要利用已知的條件,已知的條件就是已有的順序。code
public ListNode mergeKLists(ListNode[] lists) { ListNode trueHead=new ListNode(0); if(lists.length<=0) return trueHead.next; trueHead.next=lists[0]; for(int i=1;i<lists.length;i++){ ListNode cur=lists[i]; ListNode pre=trueHead; while(cur!=null){ while(pre.next!=null && pre.next.val<=cur.val) pre=pre.next; ListNode next=pre.next; ListNode curNext=cur.next; pre.next=cur; cur.next=next; cur=curNext; pre=pre.next; } } return trueHead.next; }
咱們一共會作k-1次合併,能夠經過歸併操做減小到logk次it
public ListNode mergeKLists(ListNode[] lists) { if(lists.length<=0) return null; int len=1; while(len<=lists.length){ for(int i=0;i<lists.length-len;i=i+2*len){ ListNode left=lists[i]; ListNode cur=lists[i+len]; ListNode trueHead=new ListNode(0); trueHead.next=left; ListNode pre=trueHead; while(cur!=null){ while(pre.next!=null && pre.next.val<=cur.val) pre=pre.next; ListNode next=pre.next; ListNode curNext=cur.next; pre.next=cur; cur.next=next; cur=curNext; pre=pre.next; } lists[i]=trueHead.next; } len*=2; } return lists[0]; }