标签:
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.
Example
Given lists:
[
2->4->null,
null,
-1->null
],
return -1->2->4->null
.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param lists: a list of ListNode * @return: The head of one sorted list. */ public ListNode mergeKLists(List<ListNode> lists) { // write your code here if(lists == null || lists.size() == 0) return null; PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(lists.size(), new Comparator<ListNode>(){ public int compare(ListNode p1, ListNode p2){ return p1.val - p2.val; } }); ListNode fakehead = new ListNode(0); ListNode p = fakehead; for(int i = 0; i < lists.size(); i++){ if(lists.get(i) != null) queue.offer(lists.get(i)); } while(!queue.isEmpty()){ ListNode temp = queue.poll(); p.next = temp; p = p.next; if(temp.next != null) queue.offer(temp.next); } return fakehead.next; } }
lintcode-medium-Merge k Sorted Lists
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5339822.html