【LeetCode】 023. Merge k Sorted Lists

原创 2017年01月04日 07:06:45

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

/**
 * 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.length == 0) {
            return null;
        }
        PriorityQueue<ListNode> list = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode n1, ListNode n2) {
                return n1.val - n2.val;
            }
        });
        ListNode temp = new ListNode(0);
        ListNode res = temp;
        for (ListNode subList : lists) {
            if (subList != null) {
                list.add(subList);
            }
        }
        while (!list.isEmpty()) {
            temp.next = list.poll();
            temp = temp.next;
            if (temp.next != null) {
                list.add(temp.next);
            }
        }
        return res.next;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode023 Merge k Sorted Lists

详细见:leetcode.com/problems/merge-k-sorted-lists/ 解析:两两合并(Java),堆排序(C和Python) Java Solution: g...
  • zxwtry
  • zxwtry
  • 2017年03月31日 22:03
  • 83

[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
  • 2431

[LeetCode]023-Merge K Sorted Lists

题目: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexi...

023 Merge k Sorted Lists [Leetcode]

题目内容: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its compl...

leetcode023:Merge k Sorted Lists

问题分析这个问题是leetcode021合并两个有序列表的增强版:合并k个有序列表。 实现原理比较相似:每次取k个列表表头结点,依次找出这些头结点最小的(排序,便于后续利用)。这次学习了如何利用s...

【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】

【023-Merge k Sorted Lists(合并k个排好的的单链表)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Merge k sorted linked l...

005-023-Merge k sorted lists 归并K个有序的链表

使用堆结构可以快速获得和删除最小值,平均效率是O(logn)

[LeetCode]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】 023. Merge k Sorted Lists
举报原因:
原因补充:

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