Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
1 public class Solution { 2 public ListNode mergeKLists(ArrayList<ListNode> lists) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(lists.size()==0) return null; 6 PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){ 7 public int compare(ListNode a, ListNode b){ 8 return a.val>b.val?1:(a.val==b.val?0:-1); 9 } 10 }); 11 12 for(ListNode list:lists){ 13 if(list!=null) q.add(list); 14 } 15 16 ListNode head = new ListNode(0), prev = head; 17 while(q.size()!=0){ 18 ListNode temp = q.poll(); 19 prev.next = temp; 20 if(temp.next!=null) q.add(temp.next); 21 prev = prev.next; 22 } 23 return head.next; 24 } 25 }
第二遍:
1 public class Solution { 2 public ListNode mergeKLists(ArrayList<ListNode> lists) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if(lists.size()==0) return null; 6 ListNode header = new ListNode(-1), cur = header; 7 while(true){ 8 int pos = -1; 9 for(int i = 0; i < lists.size(); i ++){ 10 if(lists.get(i) != null && (pos == -1 || lists.get(i).val < lists.get(pos).val)) 11 pos = i; 12 } 13 if(pos != -1){ 14 cur.next = lists.get(pos); 15 cur = cur.next; 16 lists.set(pos,lists.get(pos).next); 17 }else{ 18 break; 19 } 20 } 21 return header.next; 22 } 23 }
posted on 2013-10-16 07:28 Step-BY-Step 阅读(135) 评论(0) 编辑 收藏 举报