23. Merge k Sorted Lists
因为snapchat有一道题,merge log
“用电脑写一个program,可以把多个log file合并成一个,按照每个log的时间顺序排,要能运行。这不就是都读进来然后排个序然后输出吗!然后我用了大量的时间。。。搜索如何用c++进行file io。。。太丢人了。主要网速太慢!写完了给他看,能运行。OK。然后他问如何改进。我突然想到这些log file是排好序的,就说可以merge sort的方法merge进来,每个文件保持一个pointer就行。后来他问如果有很多log file呢,min heap完事儿。”
from http://www.1point3acres.com/bbs/thread-156483-1-1.html
其实就是merge k sorted lists吧
使用一个PriorityQueue,每次抽出最小的点,维持每个list的头
1 public ListNode mergeKLists(ListNode[] lists) { 2 if(lists.length == 0) { 3 return null; 4 } 5 ListNode dummy = new ListNode(-1); 6 ListNode head = dummy; 7 PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>() { 8 public int compare(ListNode l1, ListNode l2) { 9 return l1.val - l2.val; 10 } 11 }); 12 for(int i = 0; i < lists.length; i++) { 13 if(lists[i] != null) { 14 pq.offer(lists[i]); 15 } 16 } 17 while(!pq.isEmpty()) { 18 head.next = pq.poll();; 19 head = head.next; 20 if(head.next != null) { 21 pq.offer(head.next); 22 } 23 } 24 return dummy.next; 25 }

浙公网安备 33010602011771号