Question
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Solution 1 -- Merge Sort
We can follow the method of merge sort. Time complexity O(nlog(n)), n is the total number of all nodes.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if (lists == null || lists.length < 1) 12 return null; 13 if (lists.length == 1) 14 return lists[0]; 15 int k = lists.length; 16 return MSort(lists, 0, k - 1); 17 } 18 19 private ListNode MSort(ListNode[] lists, int start, int end) { 20 if (start < end) { 21 int mid = (end - start) / 2 + start; 22 ListNode left = MSort(lists, start, mid); 23 ListNode right = MSort(lists, mid + 1, end); 24 return mergeTwoLists(left, right); 25 } 26 return lists[start]; 27 } 28 29 private ListNode mergeTwoLists(ListNode a, ListNode b) { 30 ListNode newHead = new ListNode(0); 31 ListNode p = newHead, p1 = a, p2 = b; 32 while (p1 != null && p2 != null) { 33 if (p1.val < p2.val) { 34 p.next = new ListNode(p1.val); 35 p1 = p1.next; 36 } else { 37 p.next = new ListNode(p2.val); 38 p2 = p2.next; 39 } 40 p = p.next; 41 } 42 while (p1 != null) { 43 p.next = new ListNode(p1.val); 44 p1 = p1.next; 45 p = p.next; 46 } 47 while (p2 != null) { 48 p.next = new ListNode(p2.val); 49 p2 = p2.next; 50 p = p.next; 51 } 52 return newHead.next; 53 } 54 }
Solution 2 -- PriorityQueue
We can use PriorityQueue in Java. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode mergeKLists(ListNode[] lists) { 11 if (lists == null || lists.length < 1) 12 return null; 13 ListNode newHead = new ListNode(0); 14 PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(lists.length, 15 new Comparator<ListNode>() { 16 public int compare(ListNode a, ListNode b) { 17 return (a.val - b.val); 18 }}); 19 for (ListNode tmp : lists) { 20 if (tmp != null) 21 pq.add(tmp); 22 } 23 ListNode p = newHead; 24 while (pq.size() > 0) { 25 ListNode tmp = pq.poll(); 26 p.next = tmp; 27 if (tmp.next != null) 28 pq.add(tmp.next); 29 p = p.next; 30 } 31 return newHead.next; 32 } 33 }
时间: 2024-12-20 01:26:10