Hard-题目31:23. Merge k Sorted Lists

转载 2016年05月31日 23:42:58

题目原文:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题目大意:
把K个有序链表合并。
题目分析:
用一个重写比较器的优先队列,保证每次出队的都是最小的节点。
源码:(language:java)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public 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>(){
            @Override
            public int compare(ListNode o1,ListNode o2){
                if (o1.val<o2.val)
                    return -1;
                else if (o1.val==o2.val)
                    return 0;
                else 
                    return 1;
            }
        });

        ListNode dummy = new ListNode(0);
        ListNode tail=dummy;

        for (ListNode node:lists)
            if (node!=null)
                queue.add(node);

        while (!queue.isEmpty()){
            tail.next=queue.poll();
            tail=tail.next;

            if (tail.next!=null)
                queue.add(tail.next);
        }
        return dummy.next;
    }
}

成绩:
15ms,6.55%,4ms,17.34%
cmershen的碎碎念:
其实较好的办法是归并排序,但我不会写。。。
大概看了一下jdk源码,PriorityQueue的底层好像是Heap……

相关文章推荐

[LeetCode] 023. Merge k Sorted Lists (Hard) (C++/Java/Python)

[LeetCode] 023. Merge k Sorted Lists (Hard) (C++/Java/Python)
  • hcbbt
  • hcbbt
  • 2015-03-05 11:19
  • 2358

Merge k Sorted Lists (LeetCode hard algorithm problem)

本次的算法题目是Merge k Sorted Lists。 原题链接Merge k sorted linked lists and return it as one sorted list. Ana...

算法设计与分析(16)-- Merge k Sorted Lists(难度:hard)

Merge k Sorted Lists

23. Merge k Sorted Lists等题 第二周解题报告

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

leetcode23~Merge k Sorted Lists Add to List

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

【leetcode】23. Merge k Sorted Lists

合并多个已排序的单链表,多种实现方式

[leetcode] 23. Merge k Sorted Lists

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

leetcode_23_Merge k Sorted Lists

思路: 本来想模仿合并两个链表的方法,查找所有的lists链表一遍找出一个最小值,并将最小值链接到结果链表中,并将最小结点删除,将最小结点的next结点替代之,直至为null,将链表删去。 但是当l...

LeetCode_OJ【23】Merge k Sorted Lists

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

leetcode--23. Merge k Sorted Lists

leetcode
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)