-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathgwbaik9717.js
134 lines (109 loc) ยท 2.58 KB
/
gwbaik9717.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// k: len(lists), n: Total number of nodes
// Time complexity: O(nlogk)
// Space complexity: O(n)
class MinHeap {
constructor() {
this.heap = [null];
}
isEmpty() {
return this.heap.length === 1;
}
push(listNode) {
this.heap.push(listNode);
let current = this.heap.length - 1;
let parent = Math.floor(current / 2);
while (parent !== 0) {
if (this.heap[parent].val > listNode.val) {
[this.heap[parent], this.heap[current]] = [
this.heap[current],
this.heap[parent],
];
current = parent;
parent = Math.floor(current / 2);
continue;
}
break;
}
}
pop() {
if (this.heap.length === 1) {
return;
}
if (this.heap.length === 2) {
return this.heap.pop();
}
const rv = this.heap[1];
this.heap[1] = this.heap.pop();
let current = 1;
let left = current * 2;
let right = left + 1;
while (
(this.heap[left] && this.heap[current].val > this.heap[left].val) ||
(this.heap[right] && this.heap[current].val > this.heap[right].val)
) {
if (this.heap[left] && this.heap[right]) {
if (this.heap[left].val < this.heap[right].val) {
[this.heap[left], this.heap[current]] = [
this.heap[current],
this.heap[left],
];
current = left;
} else {
[this.heap[right], this.heap[current]] = [
this.heap[current],
this.heap[right],
];
current = right;
}
left = current * 2;
right = left + 1;
continue;
}
[this.heap[left], this.heap[current]] = [
this.heap[current],
this.heap[left],
];
current = left;
left = current * 2;
right = left + 1;
}
return rv;
}
}
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function (lists) {
const minHeap = new MinHeap();
for (const list of lists) {
if (list) {
minHeap.push(list);
}
}
let answer = null;
let next = null;
while (!minHeap.isEmpty()) {
const current = minHeap.pop();
if (!answer) {
answer = new ListNode();
next = answer;
}
next.val = current.val;
if (current.next) {
minHeap.push(current.next);
}
if (!minHeap.isEmpty()) {
next.next = new ListNode();
next = next.next;
}
}
return answer;
};