zoukankan      html  css  js  c++  java
  • 23. 合并K个排序链表

    一种方法是分治  类似快排的例子。

    第二种使用堆,比较好理解。  堆中保存一个元素是一个链表的头部。 

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        
        
         public ListNode mergeKLists(ListNode[] lists) {
    		 
    		  if( lists == null || lists.length == 0 )
    			  return null;
    		  
    		  PriorityQueue<ListNode> queue = 
    				  new PriorityQueue<ListNode>(lists.length, new Comparator<ListNode>() {
    					public int compare(ListNode o1, ListNode o2) {
    						return o1.val - o2.val;
    					}
    				  });
    		  
    		  ListNode dummy = new ListNode(0);
    		  ListNode cur = dummy;
    		  
    		  for(ListNode list:lists) {
    			  if( list != null )
    				  queue.add(list);
    		  }
    		  
    		  while( !queue.isEmpty() ) {
    			  
    			  cur.next = queue.poll();
    			  cur = cur.next;
    			  if( cur.next != null )
    				  queue.add(cur.next);
    		  }
    		  return dummy.next;
    	  }
        
     
            
    }
    

      

  • 相关阅读:
    SQL 通配符
    低压电器及其控制
    计算机组成原理
    ASP.NET MVC 4 跨域
    C#排序算法小结
    C# 集合扩展快速排序算法
    C# 排序算法记录
    文件大小
    ProcDump
    C# 获取文件MD5校验码
  • 原文地址:https://www.cnblogs.com/lijins/p/10148570.html
Copyright © 2011-2022 走看看