美文网首页
23. Merge k Sorted Lists

23. Merge k Sorted Lists

作者: 夜皇雪 | 来源:发表于2016-12-13 03:17 被阅读0次

list数量不多但是每个list里元素特别特别多,要用什么办法 heap
如果priorityqueue里面只剩一个list时候,可以直接merge不用在用PQ处理了
两种解法都必须会

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        return partion(lists,0,lists.length-1);
    }
    
    public static ListNode partion(ListNode[] lists,int s,int e){
        if(s==e)  return lists[s];
        if(s<e){
            int q=(s+e)/2;
            ListNode l1=partion(lists,s,q);
            ListNode l2=partion(lists,q+1,e);
            return merge(l1,l2);
        }else
            return null;
    }
    
    //This function is from Merge Two Sorted Lists.
    public static ListNode merge(ListNode l1,ListNode l2){
        if(l1==null) return l2;
        if(l2==null) return l1;
        if(l1.val<l2.val){
            l1.next=merge(l1.next,l2);
            return l1;
        }else{
            l2.next=merge(l1,l2.next);
            return l2;
        }
    }
}

相关文章

网友评论

      本文标题:23. Merge k Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/qkuvmttx.html