码迷,mamicode.com
首页 > 其他好文 > 详细

23. Merge k Sorted Lists

时间:2016-10-30 07:23:18      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:middle   for   merge   poll   heap   else   class   empty   public   

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

归并排序o(nlgk);

 

/** heap
 * 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) {
        if (lists == null || lists.length == 0)
            return null;
        else if (lists.length == 1)
            return lists[0];
        return divide(lists, 0, lists.length - 1); 
    }

    private ListNode divide(ListNode[] lists, int begin, int end) {
        if (end <= begin)
            return lists[begin];
        int middle = (begin + end) / 2;
        ListNode left = divide(lists, begin, middle);
        ListNode right = divide(lists, middle + 1, end);
        return mergeTwoList(left, right);
    }
    public ListNode mergeTwoList(ListNode l1, ListNode l2){
        if(l1 == null)
            return l2;
        if(l2 == null)
            return l1;
        if(l1.val < l2.val){
            l1.next = mergeTwoList(l1.next , l2);
            return l1;
        }
        else{
            l2.next = mergeTwoList(l1 ,l2.next);
            return l2;            
        }
    }
}

 

法二 : 优先队列

维护一个长为n的队列  o(n *lgk)

public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){
              public int compare(ListNode l1, ListNode l2){
                  return l1.val - l2.val;
              }
            });
        for(ListNode n: lists){
            if(n != null)
                queue.offer(n);
        }
        ListNode dummy = new ListNode(0);
        ListNode tail = dummy;
        while(!queue.isEmpty()){
            ListNode ln = queue.poll();
            tail.next = ln;
            tail = tail.next;
            if(ln != null && ln.next != null)
                queue.add(ln.next);
        }
        return dummy.next;
    }

 

23. Merge k Sorted Lists

标签:middle   for   merge   poll   heap   else   class   empty   public   

原文地址:http://www.cnblogs.com/joannacode/p/6012357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!