您的位置:首页 > 其它

Merge k Sorted Lists

2018-01-12 08:05 106 查看
Merge k sorted linked lists and return it as one sorted list.
Analyze and describe its complexity.

Have you met this question in a real interview? 

Yes

Example

Given lists:
[
2->4->null,
null,
-1->null
],

return 
-1->2->4->null
.
K路归并算法,使用heap的方式处理
/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if (lists == null || lists.size() == 0) {
return null;
}
ListNode dummy = new ListNode(0);
ListNode head = dummy;
Comparator<ListNode> cmp = new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
return a.val - b.val;
}
};
PriorityQueue<ListNode> heap = new PriorityQueue<>(10, cmp);
for (int i = 0; i < lists.size(); i++) {
ListNode node =  lists.get(i);
while (node != null) {
heap.offer(node);
node = node.next;
}
}
while (!heap.isEmpty()) {
head.next = heap.poll();
head = head.next;
}
return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: