题目链接:https://leetcode.com/problems/merge-k-sorted-lists/
题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题思路:
采用的数据结构是优先级队列。
将参加归并的每个链表的头结点都入队列,这样每次可以从队列中取出一个最小的结点放入新链表中,如果选中的结点的后继不为空,就让其后继入队列。
以前基本没怎么用过优先级队列,小小记录下。
优先级队列 PriorityQueue < T > 方法小结:
boolean add(E e)
Inserts the specified element into this priority queue.
E peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll()
Retrieves and removes the head of this queue, or returns null if this queue is empty.
优先级队列比较结点时采用 Comparator 接口的 compare(T o1, T o2) 方法实现。
/**
* 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(lists.length, new Comparator<ListNode>() {
@Override
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
for(int i = 0; i < lists.length; i ++) {
if(lists[i] != null)
queue.add(lists[i]);
}
ListNode res = new ListNode(0);
ListNode p = res;
while(!queue.isEmpty()) {
ListNode tmp = queue.poll();
p.next = tmp;
p = p.next;
if(tmp.next != null)
queue.add(tmp.next);
}
return res.next;
}
}
130 / 130 test cases passed.
Status: Accepted
Runtime: 424 ms