leetcode 23. Merge k Sorted Lists
2016-06-11 23:11
375 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并k个有序的链表成一个有序的链表.
用java中优先队列做,java中的优先队列是基于优先级堆的
合并k个有序的链表成一个有序的链表.
用java中优先队列做,java中的优先队列是基于优先级堆的
public class A23MergekSortedLists { // 130 test cases passed. // Runtime: 12 ms public ListNode mergeKLists(ListNode[] lists) { // 优先队列 PriorityQueue<ListNode> priorityQueue = new PriorityQueue<ListNode>(new Comparator<ListNode>() { public int compare(ListNode n1, ListNode n2) { // 升序 return n1.val - n2.val; } }); // 把每个链表的头结点加入优先队列 for(int i = 0; i < lists.length; i++) { if(lists[i] != null) { priorityQueue.add(lists[i]); } } ListNode node = new ListNode(0); ListNode ans = node; // 把优先队列中优先级最高的出队,如果它的下一个节点不为空,则把下一个节点加入优先队列中,直到队列为空 while(!priorityQueue.isEmpty()) { node.next = priorityQueue.poll(); if(node.next.next != null) { priorityQueue.add(node.next.next); } node = node.next; } return ans.next; } }后来看到有用分而治之的方法,转换成2个链表的合并.
// 130 test cases passed. // Runtime: 5 ms public ListNode mergeKLists(ListNode[] lists) { return partition(lists, 0, lists.length - 1); } public ListNode partition(ListNode[] lists, int start, int end) { if(start == end) { return lists[start]; } if(start < end) { int mid = (start + end) / 2; ListNode l1 = partition(lists, start, mid); ListNode l2 = partition(lists, mid + 1, end); return mergeTwoLists(l1, l2); } return null; } // 21. Merge Two Sorted Lists public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l2 == null) return l1; if(l1 == null) return l2; if(l1.val > l2.val) { ListNode temp = l2; temp.next = mergeTwoLists(l1, l2.next); return temp; } else { ListNode temp = l1; temp.next = mergeTwoLists(l1.next, l2); return temp; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解