-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-k-sorted-lists.java
More file actions
36 lines (31 loc) · 936 Bytes
/
Copy pathmerge-k-sorted-lists.java
File metadata and controls
36 lines (31 loc) · 936 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
ListNode dummy = new ListNode(0), tail = dummy;
while (true) {
ListNode min = null;
int idx = -1;
for (int i = 0; i < lists.length; i++) {
if (lists[i] == null) continue;
if (min == null || lists[i].val < min.val) {
min = lists[i];
idx = i;
}
}
if (min == null) break; // all lists are empty
lists[idx] = lists[idx].next;
tail.next = min;
tail = tail.next;
}
return dummy.next;
}
}