23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
合并k排序列表
合并k个已排序的链表并将其作为一个排序列表返回。分析并描述其复杂性。
第一时间想到的就是循环递归合并每个链表,直接上代码:
public class MergeKSortedLists { public ListNode mergeKLists(ListNode[] lists) { if (lists.length == 0) { return null; }else if (lists.length == 1){ return lists[0]; } ListNode res = lists[0]; for (int i = 0; i < lists.length - 1; i++) { res = dfs(res, lists[i + 1]); } return res; } public ListNode dfs(ListNode l1, ListNode l2) { if (l1 == null){ return l2; } if (l2 == null){ return l1; } if (l1.val < l2.val) { l1.next = dfs(l1.next, l2); return l1; } else { l2.next = dfs(l1, l2.next); return l2; } } public static void main(String[] args) { MergeKSortedLists mergeKSortedLists = new MergeKSortedLists(); ListNode l1 = new ListNode(1); l1.next = new ListNode(4); l1.next.next = new ListNode(5); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); ListNode l3 = new ListNode(2); l3.next = new ListNode(6); ListNode[] listNodes = {l1,l2,l3}; mergeKSortedLists.mergeKLists(listNodes); } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }
看了 vote 最高的 ac 算法,真是大开眼界。
public class Solution { public ListNode mergeKLists(List<ListNode> lists) { if (lists==null||lists.size()==0) return null; PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){ @Override public int compare(ListNode o1,ListNode o2){ if (o1.val<o2.val) return -1; else if (o1.val==o2.val) return 0; else return 1; } }); ListNode dummy = new ListNode(0); ListNode tail=dummy; for (ListNode node:lists) if (node!=null) queue.add(node); while (!queue.isEmpty()){ tail.next=queue.poll(); tail=tail.next; if (tail.next!=null) queue.add(tail.next); } return dummy.next; } }
先熟悉一下 PriorityQueue 的数据结构