Skip to content

Commit d0f755b

Browse files
authored
Update 1834-single-threaded-cpu.js
1 parent a39deff commit d0f755b

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed

1834-single-threaded-cpu.js

+109
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,112 @@
1+
/**
2+
* @param {number[][]} tasks
3+
* @return {number[]}
4+
*/
5+
const getOrder = function(tasks) {
6+
const pq = new PriorityQueue(compare), n = tasks.length
7+
const res = []
8+
let time = 0, i = 0
9+
for(let i = 0; i < n; i++) tasks[i].push(i)
10+
tasks.sort((a, b) => a[0] - b[0])
11+
12+
time = tasks[0][0]
13+
while(i < n || !pq.isEmpty()) {
14+
while ((i < n) && (tasks[i][0] <= time)) {
15+
pq.push([tasks[i][1], tasks[i][2]])
16+
i++
17+
}
18+
if(!pq.isEmpty()) {
19+
const [dur, idx] = pq.pop()
20+
time += dur
21+
res.push(idx)
22+
} else if(i < n) {
23+
time = tasks[i][0]
24+
}
25+
26+
}
27+
28+
return res
29+
};
30+
31+
function compare(a, b) {
32+
if(a[0] < b[0]) return true
33+
else if (a[0] > b[0]) return false
34+
else {
35+
return a[1] < b[1]
36+
}
37+
}
38+
39+
class PriorityQueue {
40+
constructor(comparator = (a, b) => a > b) {
41+
this.heap = []
42+
this.top = 0
43+
this.comparator = comparator
44+
}
45+
size() {
46+
return this.heap.length
47+
}
48+
isEmpty() {
49+
return this.size() === 0
50+
}
51+
peek() {
52+
return this.heap[this.top]
53+
}
54+
push(...values) {
55+
values.forEach((value) => {
56+
this.heap.push(value)
57+
this.siftUp()
58+
})
59+
return this.size()
60+
}
61+
pop() {
62+
const poppedValue = this.peek()
63+
const bottom = this.size() - 1
64+
if (bottom > this.top) {
65+
this.swap(this.top, bottom)
66+
}
67+
this.heap.pop()
68+
this.siftDown()
69+
return poppedValue
70+
}
71+
replace(value) {
72+
const replacedValue = this.peek()
73+
this.heap[this.top] = value
74+
this.siftDown()
75+
return replacedValue
76+
}
77+
78+
parent = (i) => ((i + 1) >>> 1) - 1
79+
left = (i) => (i << 1) + 1
80+
right = (i) => (i + 1) << 1
81+
greater = (i, j) => this.comparator(this.heap[i], this.heap[j])
82+
swap = (i, j) => ([this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]])
83+
siftUp = () => {
84+
let node = this.size() - 1
85+
while (node > this.top && this.greater(node, this.parent(node))) {
86+
this.swap(node, this.parent(node))
87+
node = this.parent(node)
88+
}
89+
}
90+
siftDown = () => {
91+
let node = this.top
92+
while (
93+
(this.left(node) < this.size() && this.greater(this.left(node), node)) ||
94+
(this.right(node) < this.size() && this.greater(this.right(node), node))
95+
) {
96+
let maxChild =
97+
this.right(node) < this.size() &&
98+
this.greater(this.right(node), this.left(node))
99+
? this.right(node)
100+
: this.left(node)
101+
this.swap(node, maxChild)
102+
node = maxChild
103+
}
104+
}
105+
}
106+
107+
108+
// another
109+
1110
/**
2111
* @param {number[][]} tasks
3112
* @return {number[]}

0 commit comments

Comments
 (0)