-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmerge-k-sorted-lists.js
45 lines (41 loc) · 1.1 KB
/
merge-k-sorted-lists.js
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
37
38
39
40
41
42
43
44
45
/**
* Definition for singly-linked list.
function ListNode(val) {
this.val = val;
this.next = null;
}
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
var mergedList = new ListNode();
var currentNode = mergedList;
for (var i = 0; i < lists.length;) {
if (!lists[i]) {
lists.splice(i, 1);
} else {
i++;
}
}
lists = lists.sort(sortByValue);
while(lists.length > 0) {
currentNode.next = lists[0];
currentNode = currentNode.next;
lists[0].next ? (lists[0] = lists[0].next) : (lists.splice(0, 1));
lists = lists.length > 0 ? simpleSort(lists): [];
}
return mergedList.next;
};
function simpleSort(lists) {
for (var i = 0, j = lists.length; i < j - 1; i++) {
if (lists[0].val >= lists[i].val && lists[0].val <= lists[i+1].val) {
return lists.slice(1, i + 1).concat(lists[0]).concat(lists.slice(i + 1))
}
}
return lists.slice(1, i+1).concat(lists[0]);
}
function sortByValue(a, b) {
return a.val - b.val;
}