zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    hdu1087Super Jumping! Jumping! Jumping!
    hdu1159Common Subsequence(最长公共子序列)
    hdu1069Monkey and Banana(最长递增子序列)
    poj2533(最长递增子序列)
    hdu1029Ignatius and the Princess IV
    uva10622(唯一分解定理)
    myeclipse设置技巧
    myeclipse2014新感悟
    小错误汇总
    字符串反转
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3371432.html
Copyright © 2011-2022 走看看