Saturday, November 14, 2015

[leetcode] Merge k sorted lists

Almost forget the properties of Link list
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>(){
           public int compare(ListNode n1, ListNode n2){
               return n1.val-n2.val;
           } 
        });
        for (int i = 0; i < lists.length; i++){
            if (lists[i] != null){
                queue.add(lists[i]);
            }
        }
        ListNode dummy = new ListNode(-1);
        ListNode previous = dummy;
        while (!queue.isEmpty()){
            ListNode temp = queue.poll();
            previous.next = temp;
            if (temp.next != null){
                queue.add(temp.next);
            }
            previous = previous.next;
        }
        return dummy.next;
    }
}

No comments:

Post a Comment