Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c306266

Browse files
committed
merge k sorted list
1 parent 5de5705 commit c306266

File tree

3 files changed

+49
-61
lines changed

3 files changed

+49
-61
lines changed

‎src/main/java/grey/algorithm/Code_0031_LeetCode_0023_MergeKSortedLists.java

Lines changed: 0 additions & 58 deletions
This file was deleted.

‎src/main/java/grey/algorithm/code11_heap/Code_0003_HeapSort.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@
1414
public class Code_0003_HeapSort {
1515
public static void heapSort1(int[] arr) {
1616
for (int i = 0; i < arr.length; i++) {
17-
heapInsert(arr,i);
17+
heapInsert(arr,i);
1818
}
1919
// 大根堆
2020
// 此时,最大元素已经在0号位置
2121
int size = arr.length;
2222
while (size > 0) {
23-
swap(arr, 0,--size);
24-
heapify(arr, 0, size);
23+
swap(arr, 0,--size);
24+
heapify(arr, 0, size);
2525
}
2626
}
2727

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package grey.algorithm.code11_heap;
2+
3+
import java.util.PriorityQueue;
4+
5+
// 测评链接:https://leetcode.com/problems/merge-k-sorted-lists/
6+
// 把每个链表的头节点加入到小根堆中
7+
// 然后弹出一个元素X,然后从这个弹出元素的下一个元素开始和堆顶元素比
8+
// 如果X比堆顶元素大,则堆顶元素弹出,X进入小根堆
9+
// 如果X比堆顶元素小,则直接不需要进入堆顶,作为结果链表
10+
// https://www.cnblogs.com/greyzeng/p/7551789.html
11+
public class Code_0004_LeetCode_0023_MergeKSortedLists {
12+
13+
public ListNode mergeKLists(ListNode[] lists) {
14+
if (null == lists || lists.length < 1) {
15+
return null;
16+
}
17+
PriorityQueue<ListNode> heap = new PriorityQueue<>((o1, o2) -> (o1.val - o2.val));
18+
for (ListNode node : lists) {
19+
if (null != node) {
20+
heap.offer(node);
21+
}
22+
}
23+
if (heap.isEmpty()) {
24+
return null;
25+
}
26+
ListNode head = heap.poll();
27+
if (head.next != null) {
28+
heap.offer(head.next);
29+
}
30+
ListNode cur = head;
31+
while (!heap.isEmpty()) {
32+
ListNode node = heap.poll();
33+
cur.next = node;
34+
if (node.next != null) {
35+
heap.offer(node.next);
36+
}
37+
cur = cur.next;
38+
}
39+
return head;
40+
}
41+
42+
public class ListNode {
43+
int val;
44+
ListNode next;
45+
}
46+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /