您的位置:首页 > 其它

LeetCode: Merge k Sorted Lists 解题报告

2014-12-05 10:37 405 查看
Merge k Sorted Lists

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

Show Tags

/*
SOL 2:
使用 priority Queue.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// 记得加上这个合法性判断。
if (lists == null || lists.size() == 0) {
return null;
}

int size = lists.size();

PriorityQueue<ListNode> q = new PriorityQueue<ListNode>(size,
new Comparator<ListNode>() {
// 注意,此处参数用ListNode
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
}
);

// Add all the head node to the priority queue.
for (ListNode node: lists) {
if (node != null) {
// Should skip the null node.s
q.offer(node);
}
}

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

while (!q.isEmpty()) {
// get the smallest node from the queue.
ListNode cur = q.poll();

tail.next = cur;
tail = tail.next;

// 将下一个节点补充进来。
if (cur.next != null) {
q.offer(cur.next);
}
}

return dummy.next;
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/MergeKLists_1204.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: