LeetCode 23. Merge k Sorted Lists Posted on 2017-06-25 | In LeetCode | Question Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Explanation 见code。 Code 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { // Solution 1: heap // private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>(){ // public int compare(ListNode left, ListNode right){ // return left.val - right.val; // } // }; // public ListNode mergeKLists(ListNode[] lists) { // if (lists == null || lists.length == 0 ) return null; // Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.length, ListNodeComparator); // for (int i=0; i<lists.length; i++) { // if (lists[i] != null) { // heap.add(lists.get(i)); // } // } // ListNode dummy = new ListNode(0); // ListNode tail = dummy; // while(!heap.isEmpty()) { // ListNode head = heap.poll(); // tail.next = head; // tail = head; // if (head.next != null) { // heap.add(head.next); // } // } // return dummy.next; // } // Solution 2: merge two by two public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; return partition(lists, 0, lists.length - 1); } public ListNode partition(ListNode[] lists, int start, int end) { if (start == end) return lists[start]; if (start < end) { int middle = (start + end) / 2; ListNode n1 = partition(lists, start, middle); ListNode n2 = partition(lists, middle+1, end); return merge(n1, n2); } return null; } public static ListNode merge(ListNode n1, ListNode n2) { if (n1 == null) return n2; if (n2 == null) return n1; if (n1.val < n2.val) { n1.next = merge(n1.next, n2); return n1; } else { n2.next = merge(n1, n2.next); return n2; } }}