23 Merged K sorted lists

  • 第一个方法,brute force,把所有elements收集到arraylist,然后sort,然后存到linked list。
public ListNode mergeKLists(ListNode[] lists) {
    List<Integer> l = new ArrayList<Integer>();
    //存到数组
    for (ListNode ln : lists) {
        while (ln != null) {
            l.add(ln.val);
            ln = ln.next;
        }
    }
    //数组排序
    Collections.sort(l);
    //存到链表
    ListNode head = new ListNode(0);
    ListNode h = head;
    for (int i : l) {
        ListNode t = new ListNode(i);
        h.next = t;
        h = h.next;
    }
    h.next = null;
    return head.next;
}

 

随后像merged two SOrted Lists一样,两辆合并。但是也有小技巧,s.h.i.t

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode h = new ListNode(0);
    ListNode ans=h;
    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            h.next = l1;
            h = h.next;
            l1 = l1.next;
        } else {
            h.next = l2;
            h = h.next;
            l2 = l2.next;
        }
    }
    if(l1==null){
        h.next=l2;
    }
    if(l2==null){
        h.next=l1;
    } 
    return ans.next;
}
public ListNode mergeKLists(ListNode[] lists) {
    if(lists.length==1){
        return lists[0];
    }
    if(lists.length==0){
        return null;
    }
    ListNode head = mergeTwoLists(lists[0],lists[1]);//返回的总是排好序的第一个节点
    for (int i = 2; i < lists.length; i++) {
        head = mergeTwoLists(head,lists[i]);//然后和后一个开始交♂换
    }
    return head;
}

 吐槽啊,笨方法比正常方法快8倍还行

public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)
            return null;
 
        //PriorityQueue is a sorted queue
        PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.length,
                new Comparator<ListNode>() {
                    public int compare(ListNode a, ListNode b) {
                        return a.val - b.val;
                    }
                });
 
        //add first node of each list to the queue
        for (ListNode list : lists) {
            if (list != null)
                q.add(list);
        }
 
        ListNode head = new ListNode(0);
        ListNode p = head; // serve as a pointer/cursor
 
        while (q.size() > 0) {
            ListNode temp = q.poll();
            //poll() retrieves and removes the head of the queue - q. 
            p.next = temp;
 
            //keep adding next element of each list
            if (temp.next != null)
                q.add(temp.next);
 
            p = p.next;
        }
 
        return head.next;
    }
}

最好的方法是“可以将k个sorted list想象成k个有序数据流,互相竞争插入到结果序列, 因此可以考虑使用一个最小值堆维护动态数据:将每个队头的元素加入一个堆,然后从堆中依次弹出最小数据。如果数据属于第i个list,则该list补充一个元素到堆。重复上述过程直到所有元素排序完成。事实上,该算法就是外排序算法的一个具体实现,区别仅仅在于这里略去了文件的读写操作。”https://wdxtub.com/interview/14520597851075.html

priorityqueue与最小堆:https://www.jianshu.com/p/c577796e537a

posted @ 2019-02-01 05:24  Schwifty  阅读(177)  评论(0)    收藏  举报