F_G

许多问题需要说清楚就可以&&走永远比跑来的重要

导航

Merge k Sorted Lists

leetcode

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

使用一个大小为K的堆来维持找当前的最小元素。

一、Java当中的PriorityQueue如何使用?

class ListNode {
   int val;
   ListNode next;
   ListNode(int x) { val = x; }
}

对于上面的节点,需要重新实现Comparator接口

实现方式为:

class MyCompare implements Comparator{
    public int compare(Object o1, Object o2){
        ListNode n1 = (ListNode)o1;
        ListNode n2 = (ListNode)o2;
        if(n1.val < v2.val){
            return -1;
        }else if(n1.val==n2.val){
            return 0;
        }else{
            return 1;
        }
    }
}

注意上面的定义方式,对于升序排列,则当小于时返回-1,大于时返回1,else 返回 0.

另外也可以也可以使用匿名函数的方式。

Comparator<ListNode> mc = new Comparator<ListNode>(){
            public int compare(ListNode n1, ListNode n2){
                //should pay attention to the return value below
                if(n1.val < n2.val){
                    return -1;
                }else if(n1.val==n2.val){
                    return 0;
                }else{
                    return 1;
                }
            }
        };

算法总体的代码实现为:

public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists==null||lists.length==0) return null;
        Comparator<ListNode> mc = new Comparator<ListNode>(){
            public int compare(ListNode n1, ListNode n2){
                //should pay attention to the return value below
                if(n1.val < n2.val){
                    return -1;
                }else if(n1.val==n2.val){
                    return 0;
                }else{
                    return 1;
                }
            }
        };
     //这里需要注意,在新的java版本当中,不能指定泛型的类型,也就是下面的代码如果定义为Queue<ListNode> queue = new PriorityQueue<ListNode>(lists.length,mc);会报错
     //实际当中,应该是把其当做Object来看待的,在实际使用时,可以对其进行强制类型转化,即可
Queue queue
= new PriorityQueue(lists.length,mc); for(int i=0;i<lists.length;i++){ //there may be the contents in the lists is null, this is a corner case if(lists[i]!=null) queue.add(lists[i]); } ListNode head=null; ListNode prenode=null; while(!queue.isEmpty()){ ListNode top = (ListNode)queue.poll(); ListNode next = top.next; top.next=null; if(head==null){ head=top; prenode=top; }else{ prenode.next=top; prenode=top; } if(next!=null){ queue.add(next); } } return head; } }

 

 

posted on 2015-06-15 17:03  F_G  阅读(184)  评论(0编辑  收藏  举报