LeetCode 023 Merge k Sorted Lists
2015-03-19 14:21
363 查看
题目
把k个排序号的链表连接成一个有序链表。
代码
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null){
return null;
}
PriorityQueue<ListNode> record =
new PriorityQueue<ListNode>(
new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
for(Iterator<ListNode> i =lists.iterator();i.hasNext();){
ListNode cur = i.next();
while(cur !=null){
record.add(cur);
cur = cur.next;
}
}
ListNode dummy = new ListNode(Integer.MAX_VALUE);
ListNode curNode = dummy;
while(!record.isEmpty()){
curNode.next=new ListNode(record.poll().val);
curNode = curNode.next;
}
return dummy.next;
}
}
思考
1 时间:Nlog(k) N 是总数 log(k)是每次插入堆或者取出堆的需要操作的次数
2 可以换divide and conquar来做,时间一样
把k个排序号的链表连接成一个有序链表。
代码
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if(lists == null){
return null;
}
PriorityQueue<ListNode> record =
new PriorityQueue<ListNode>(
new Comparator<ListNode>() {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
for(Iterator<ListNode> i =lists.iterator();i.hasNext();){
ListNode cur = i.next();
while(cur !=null){
record.add(cur);
cur = cur.next;
}
}
ListNode dummy = new ListNode(Integer.MAX_VALUE);
ListNode curNode = dummy;
while(!record.isEmpty()){
curNode.next=new ListNode(record.poll().val);
curNode = curNode.next;
}
return dummy.next;
}
}
思考
1 时间:Nlog(k) N 是总数 log(k)是每次插入堆或者取出堆的需要操作的次数
2 可以换divide and conquar来做,时间一样
相关文章推荐
- 2017-09-11 LeetCode_023 Merge k Sorted Lists
- [LeetCode]题解(python):023-Merge k Sorted Lists
- leetcode_023 Merge k Sorted Lists
- leetcode 023 —— Merge k sorted linked lists
- leetcode解题方案--023--Merge k Sorted Lists
- leetcode_c++:链表:Merge k Sorted Lists(023)
- LeetCode 023 Merge k Sorted Lists
- LeetCode-023 Merge k Sorted Lists
- 023 Merge k Sorted Lists [Leetcode]
- [LeetCode]023-Merge K Sorted Lists
- Java for LeetCode 023 Merge k Sorted Lists
- 【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】
- [LeetCode] Merge k Sorted Lists
- LeetCode Merge Two Sorted Lists
- leetcode-23Merge k Sorted Lists
- leetcode Merge k Sorted Lists
- Leetcode:Merge Two Sorted Lists 合并两个有序单链表
- 【LeetCode】Merge k Sorted Lists
- [Leetcode]-Merge Two Sorted Lists
- leetcode 之 Merge k Sorted Lists