题目:合并k个排序链表

来源:互联网 发布:全球域名注册局 编辑:程序博客网 时间:2024/05/17 07:59

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


您在真实的面试中是否遇到过这个题?

Yes





样例

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



相关题目 Expand 
解题思路:
若是每次2个2个去进行合并,超时。
故选择2分法
/*** 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(0==lists.size()||null==lists){              return null;         }         if(lists.size()==1){              return lists.get(0);         }         //用2分法         int  mid = (lists.size()-1)/2+1;         ListNode left = mergeKLists(lists.subList(0, mid));         ListNode right = mergeKLists(lists.subList(mid, lists.size()));         return merge2(left, right);            }    public ListNode merge2(ListNode l1,ListNode l2){         if(l1==null) return l2;         if(l2==null) return l1;         ListNode res = new ListNode(-1);         ListNode cur = res;         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 res.next;    }}

0 0