Skip to content

Commit 3cfe48c

Browse files
authored
Create 1834-single-threaded-cpu.js
1 parent 3a07eb4 commit 3cfe48c

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

1834-single-threaded-cpu.js

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

0 commit comments

Comments
 (0)