LeetCode23 – Merge k Sorted Lists (Java)
2016-08-31 22:15
120 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Analysis
The simplest solution is using PriorityQueue. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case).
Java Solution
Analysis
The simplest solution is using PriorityQueue. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case).
Java Solution
public ListNode mergeKLists(ListNode[] lists) { if(lists==null||lists.length==0) return null; PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(new Comparator<ListNode>(){ public int compare(ListNode l1, ListNode l2){ return l1.val - l2.val; } }); ListNode head = new ListNode(0); ListNode p = head; for(ListNode list: lists){ if(list!=null) queue.offer(list); } while(!queue.isEmpty()){ ListNode n = queue.poll(); p.next = n; p=p.next; if(n.next!=null) queue.offer(n.next); } return head.next; }
相关文章推荐
- (java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- Merge k Sorted Lists leetcode java
- leetcode:Merge k Sorted Lists 【Java】
- LeetCode : Merge Two Sorted Lists [java]
- LeetCode : Merge k Sorted Lists [java]
- Merge k Sorted Lists Java
- [Leetcode] Merge k Sorted Lists (Java)
- 【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】
- [LeetCode][Java] Merge Two Sorted Lists
- leetcode:Merge Two Sorted Lists 【Java】
- LeetCode 21 — Merge Two Sorted Lists(C++ Java Python)
- LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)
- Merge k Sorted Lists (Java)
- Java [leetcode 23]Merge k Sorted Lists
- [Leetcode] Merge Two Sorted Lists (Java)
- Merge Two Sorted Lists (Java)
- Java for LeetCode 023 Merge k Sorted Lists
- LeetCode23 Merge k Sorted Lists 把K个有序链表连接成一个
- 【LeetCode】Merge Two Sorted Lists 解题报告(Java & Python)
- LeetCode 23 Merge k Sorted Lists (C,C++,Java,Python)