Skip to content

Commit f74220c

Browse files
committed
MergeKSortedLists23
1 parent 1e929a5 commit f74220c

2 files changed

Lines changed: 57 additions & 2 deletions

File tree

src/MergeKSortedLists23.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,59 @@ private ListNode mL(ListNode[] lists, int l, int r) {
110110
return dmHead.next;
111111
}
112112

113+
114+
public ListNode mergeKLists4(ListNode[] lists) {
115+
if (lists == null || lists.length == 0) return null;
116+
ListNode dummy = new ListNode(0);
117+
ListNode p = dummy;
118+
PriorityQueue<ListNode> q = new PriorityQueue<ListNode>((l1, l2) -> Integer.compare(l1.val, l2.val));
119+
for (ListNode node: lists) {
120+
if (node != null) q.add(node);
121+
}
122+
while (!q.isEmpty()) {
123+
ListNode curr = q.poll();
124+
if (curr.next != null) q.add(curr.next);
125+
curr.next = null;
126+
p.next = curr;
127+
p = p.next;
128+
}
129+
130+
return dummy.next;
131+
}
132+
133+
134+
public ListNode mergeKLists5(ListNode[] lists) {
135+
if (lists == null || lists.length == 0) return null;
136+
137+
int len = lists.length;
138+
int interval = 1;
139+
while (interval < len) {
140+
for (int i=0; i < len-interval; i+=interval*2)
141+
lists[i] = mergeTwoLists5(lists[i], lists[i + interval]);
142+
interval *= 2;
143+
}
144+
145+
return lists[0];
146+
}
147+
148+
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
149+
ListNode dummy = new ListNode(0);
150+
ListNode p = dummy;
151+
while (l1 != null && l2 != null) {
152+
if (l1.val >= l2.val) {
153+
p.next = l2;
154+
l2 = l2.next;
155+
} else {
156+
p.next = l1;
157+
l1 = l1.next;
158+
}
159+
p = p.next;
160+
p.next = null;
161+
}
162+
if (l1 != null) p.next = l1;
163+
if (l2 != null) p.next = l2;
164+
return dummy.next;
165+
}
166+
167+
113168
}

src/MergeTwoSortedLists21.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
4343
if (l2 == null) return l1;
4444

4545
if (l1.val >= l2.val) {
46-
l2.next = mergeTwoLists(l1, l2.next);
46+
l2.next = mergeTwoLists2(l1, l2.next);
4747
return l2;
4848
} else {
49-
l1.next = mergeTwoLists(l1.next, l2);
49+
l1.next = mergeTwoLists2(l1.next, l2);
5050
return l1;
5151
}
5252
}

0 commit comments

Comments
 (0)