多路归并排序 merge k sorted array, merge k sorted linked list
2012-10-07 04:40
316 查看
归并k个有序数组,merge k sorted array
归并k个有序链表,merge k sorted linked list
给定k个有序数组,每个长度都是n,把这k个数组归并成一个有序数组。例如:
算法:
构建一个长度是n*k的空数组。
从k个数组中,取出每个数组的第一个元素,构建一个最小堆。
把最小堆的根结点的元素放入结果中,并记下根结点元素来自哪个数组。
删除最小堆的顶点元素。
如果那个数组不空,从那个数组取下一个元素,放入堆中。
维护最小堆。
1. Create an output array of
size n*k.
2. Create a min heap of size k and
insert 1st element in all the arrays into a the heap
3. Repeat following steps n*k times.
a) Get
minimum element from heap (minimum is always at root) and store it in output array.
b) Replace
heap root with next element from the array from which the element is extracted. If the array doesn’t have any more elements, then replace root with infinite. After replacing the root, heapify the tree.
算法详见:http://www.geeksforgeeks.org/merge-k-sorted-arrays/
归并k个有序链表,merge k sorted linked list
给定k个有序数组,每个长度都是n,把这k个数组归并成一个有序数组。例如:
Input: k = 3, n = 4 arr[][] = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}} ; Output: 0 1 2 3 4 5 6 7 8 9 10 11
算法:
构建一个长度是n*k的空数组。
从k个数组中,取出每个数组的第一个元素,构建一个最小堆。
把最小堆的根结点的元素放入结果中,并记下根结点元素来自哪个数组。
删除最小堆的顶点元素。
如果那个数组不空,从那个数组取下一个元素,放入堆中。
维护最小堆。
1. Create an output array of
size n*k.
2. Create a min heap of size k and
insert 1st element in all the arrays into a the heap
3. Repeat following steps n*k times.
a) Get
minimum element from heap (minimum is always at root) and store it in output array.
b) Replace
heap root with next element from the array from which the element is extracted. If the array doesn’t have any more elements, then replace root with infinite. After replacing the root, heapify the tree.
算法详见:http://www.geeksforgeeks.org/merge-k-sorted-arrays/
相关文章推荐
- Merge Sorted Array leetcode java(回顾MergeTwoArray和MergeTwoLinkedList)
- merge two sorted linked list without duplicates
- 常用数据结构及复杂度 array、LinkedList、List、Stack、Queue、Dictionary、SortedDictionary、HashSet、SortedSet
- (java) Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- 【Leetcode】Merge K Sorted Linked List
- LeetCode[Linked List]: Merge k Sorted Lists
- LinkedList-21-Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- LeetCode -- Merge Two Sorted Linked List
- LeetCode@LinkedList_21_Merge_Two_Sorted_Lists
- Remove Duplicates from Sorted List && Merge Two Sorted Lists && Linked List Cycle && Remove Nth Node
- merge two sorted linked list with duplicates
- LeetCode 学习 LinkedList 专项(4)—— Merge Two Sorted Lists
- Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- LeetCode_Linked List_Merge Two Sorted Lists
- 21. Merge Two Sorted Lists(Linked List-Easy)
- Merge Sort Array --> Merge Sort Linked List --> Insertion Sort Array --> Insertion sort Linked List
- 【LeetCode】【Linked List】Merge Two Sorted Lists
- 88/19 Merge Sorted Array/Remove Nth Node From End of List(指针运算)
- 21. Merge Two Sorted Lists(Linked List)